diff --git a/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts b/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts index b4fcba49b..b55d3282a 100755 --- a/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts +++ b/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts @@ -1,6 +1,7 @@ /*! Copyright [Amazon.com](http://amazon.com/), Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ import * as fs from "fs"; +import * as util from "util"; import SwaggerParser from "@apidevtools/swagger-parser"; import { parse } from "ts-command-line-args"; import * as ejs from "ejs"; @@ -359,6 +360,10 @@ const toTypeScriptType = (property: parseOpenapi.Model): string => { return `Array<${property.link && property.link.export !== "enum" ? toTypeScriptType(property.link) : property.type}>`; case "dictionary": return `{ [key: string]: ${property.link && property.link.export !== "enum" ? toTypeScriptType(property.link) : property.type}; }`; + case "one-of": + case "any-of": + case "all-of": + return property.name; default: return property.type; } @@ -412,6 +417,10 @@ const toJavaType = (property: parseOpenapi.Model): string => { return `${property.uniqueItems ? 'Set' : 'List'}<${property.link && property.link.export !== "enum" ? toJavaType(property.link) : property.type}>`; case "dictionary": return `Map`; + case "one-of": + case "any-of": + case "all-of": + return property.name; default: // "any" has export = interface if (PRIMITIVE_TYPES.has(property.type)) { @@ -461,6 +470,10 @@ const toPythonType = (property: parseOpenapi.Model): string => { return `List[${property.link && property.link.export !== "enum" ? toPythonType(property.link) : property.type}]`; case "dictionary": return `Dict[str, ${property.link && property.link.export !== "enum" ? toPythonType(property.link) : property.type}]`; + case "one-of": + case "any-of": + case "all-of": + return property.name; default: // "any" has export = interface if (PRIMITIVE_TYPES.has(property.type)) { @@ -649,7 +662,7 @@ const filterInlineCompositeSchemas = (schemas: (OpenAPIV3.SchemaObject | OpenAPI let inlineSchemaIndex = 0; return schemas.flatMap((s, i) => { if (hasSubSchemasToVisit(s)) { - const subSchema: SubSchema = { nameParts: [...nameParts, `${namePartPrefix}${inlineSchemaIndex === 0 ? '' : inlineSchemaIndex}`], schema: s, prop: `${prop}.[${i}]` }; + const subSchema: SubSchema = { nameParts: s.title ? [_upperFirst(_camelCase(s.title))] : [...nameParts, `${namePartPrefix}${inlineSchemaIndex === 0 ? '' : inlineSchemaIndex}`], schema: s, prop: `${prop}.[${i}]` }; inlineSchemaIndex++; return [subSchema]; } @@ -1034,7 +1047,7 @@ export default async (argv: string[], rootScriptDir: string) => { const data = await buildData(spec, JSON.parse(args.metadata ?? '{}')); if (args.printData) { - console.log(JSON.stringify(data, null, 2)); + console.log(util.inspect(data, { depth: 100 })); } // Read all .ejs files in each template directory diff --git a/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs b/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs index 78d5c434e..a28a68295 100644 --- a/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs +++ b/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs @@ -62,8 +62,8 @@ export type <%- model.name %> =<% model.properties.forEach((composedType, i) => <%_ } _%> */ export interface <%= model.name %> { -<%_ if (model.additionalProperties) { _%> - [key: string]: <%- model.additionalProperties.typescriptType %>; +<%_ if (model.export === "dictionary" && model.link) { _%> + [key: string]: <%- model.link.typescriptType %>; <%_ } _%> <%_ model.properties.forEach((property) => { _%> /** @@ -126,7 +126,7 @@ export function <%= model.name %>FromJSONTyped(json: any, ignoreDiscriminator: b <%_ } else { _%> return { -<%_ if (model.additionalProperties) { _%> +<%_ if (model.export === "dictionary") { _%> ...json, <%_ } _%> <%_ model.properties.forEach((property) => { _%> @@ -173,7 +173,7 @@ export function <%= model.name %>ToJSON(value?: <%= model.name %> | null): any { <%_ } else { _%> return { -<%_ if (model.additionalProperties) { _%> +<%_ if (model.export === "dictionary") { _%> ...value, <%_ } _%> <%_ model.properties.forEach((property) => { _%> diff --git a/packages/type-safe-api/test/resources/specs/edge-cases.yaml b/packages/type-safe-api/test/resources/specs/edge-cases.yaml index 0e430b00b..cf100a7a6 100644 --- a/packages/type-safe-api/test/resources/specs/edge-cases.yaml +++ b/packages/type-safe-api/test/resources/specs/edge-cases.yaml @@ -118,6 +118,36 @@ paths: string required: - someProperty + /named-one-of: + post: + operationId: namedOneOf + responses: + 200: + description: ok + content: + application/json: + schema: + $ref: "#/components/schemas/NamedOneOfUnion" + /array-of-one-ofs: + post: + operationId: arrayOfOneOfs + responses: + 200: + description: ok + content: + application/json: + schema: + $ref: "#/components/schemas/ArrayOfOneOfs" + /additional-properties: + post: + operationId: dictionary + responses: + 200: + description: ok + content: + application/json: + schema: + $ref: "#/components/schemas/AdditionalPropertiesResponse" components: schemas: MyEnum: @@ -125,4 +155,43 @@ components: enum: - one - two - - three \ No newline at end of file + - three + NamedOneOfUnion: + oneOf: + - type: object + title: namedOneOf + properties: + foo: + type: string + - type: object + title: anotherNamedOneOf + properties: + bar: + type: string + ArrayOfOneOfs: + type: object + properties: + oneOfs: + type: array + items: + $ref: "#/components/schemas/NamedOneOfUnion" + AdditionalPropertiesResponse: + type: object + properties: + dictionaryOfObjects: + $ref: "#/components/schemas/Dictionary" + dictionaryOfPrimitives: + type: object + additionalProperties: + type: string + Dictionary: + type: object + additionalProperties: + type: array + items: + $ref: "#/components/schemas/SomeObject" + SomeObject: + type: object + properties: + a: + type: string diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap index 5d196168a..9cdcbc318 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap @@ -30333,29 +30333,47 @@ src/main/java/test/test/runtime/api/handlers/RequestInput.java src/main/java/test/test/runtime/api/handlers/ChainedRequestInput.java src/main/java/test/test/runtime/api/handlers/InterceptorWarmupChainedRequestInput.java src/main/java/test/test/runtime/api/handlers/InterceptorWithWarmup.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsResponse.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersResponse.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryResponse.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfResponse.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsResponse.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs200Response.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters200Response.java +src/main/java/test/test/runtime/api/handlers/dictionary/Dictionary200Response.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum200Response.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody204Response.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf200Response.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords200Response.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestParameters.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestParameters.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryRequestParameters.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestParameters.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestParameters.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestParameters.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestParameters.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsInput.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersInput.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryInput.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfInput.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsInput.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestInput.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestInput.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryRequestInput.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestInput.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestInput.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters.java +src/main/java/test/test/runtime/api/handlers/dictionary/Dictionary.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java src/main/java/test/test/runtime/api/handlers/HandlerRouter.java src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java @@ -30386,10 +30404,17 @@ src/main/java/test/test/runtime/ServerConfiguration.java src/main/java/test/test/runtime/ServerVariable.java src/main/java/test/test/runtime/StringUtil.java src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java +src/main/java/test/test/runtime/model/AdditionalPropertiesResponse.java +src/main/java/test/test/runtime/model/AnotherNamedOneOf.java +src/main/java/test/test/runtime/model/ArrayOfOneOfs.java +src/main/java/test/test/runtime/model/Dictionary.java src/main/java/test/test/runtime/model/InlineEnum200Response.java src/main/java/test/test/runtime/model/InlineEnum200ResponseCategoryEnum.java src/main/java/test/test/runtime/model/InlineRequestBodyRequestContent.java -src/main/java/test/test/runtime/model/MyEnum.java", +src/main/java/test/test/runtime/model/MyEnum.java +src/main/java/test/test/runtime/model/NamedOneOf.java +src/main/java/test/test/runtime/model/NamedOneOfUnion.java +src/main/java/test/test/runtime/model/SomeObject.java", "src/main/java/test/test/runtime/ApiCallback.java": "/* * Edge Cases * @@ -32456,8 +32481,15 @@ public class JSON { gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AdditionalPropertiesResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AnotherNamedOneOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.ArrayOfOneOfs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.Dictionary.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.InlineEnum200Response.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.InlineRequestBodyRequestContent.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.NamedOneOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.NamedOneOfUnion.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.SomeObject.CustomTypeAdapterFactory()); gson = gsonBuilder.create(); } @@ -33158,9 +33190,12 @@ import java.io.IOException; import java.math.BigDecimal; import java.io.File; +import test.test.runtime.model.AdditionalPropertiesResponse; +import test.test.runtime.model.ArrayOfOneOfs; import test.test.runtime.model.InlineEnum200Response; import test.test.runtime.model.InlineRequestBodyRequestContent; import test.test.runtime.model.MyEnum; +import test.test.runtime.model.NamedOneOfUnion; import java.lang.reflect.Type; import java.util.ArrayList; @@ -33206,6 +33241,151 @@ public class DefaultApi { this.localCustomBaseUrl = customBaseUrl; } + private okhttp3.Call arrayOfOneOfsCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/array-of-one-ofs"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + + @SuppressWarnings("rawtypes") + private okhttp3.Call arrayOfOneOfsValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return arrayOfOneOfsCall(_callback); + + } + + private ApiResponse arrayOfOneOfsWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = arrayOfOneOfsValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + + private okhttp3.Call arrayOfOneOfsAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = arrayOfOneOfsValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIarrayOfOneOfsRequest { + + private APIarrayOfOneOfsRequest() { + } + + /** + * Build call for arrayOfOneOfs + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return arrayOfOneOfsCall(_callback); + } + + /** + * Execute arrayOfOneOfs request + * @return ArrayOfOneOfs + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ArrayOfOneOfs execute() throws ApiException { + ApiResponse localVarResp = arrayOfOneOfsWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Execute arrayOfOneOfs request with HTTP info returned + * @return ApiResponse<ArrayOfOneOfs> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return arrayOfOneOfsWithHttpInfo(); + } + + /** + * Execute arrayOfOneOfs request (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 + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return arrayOfOneOfsAsync(_callback); + } + } + + /** + * + * + * @return APIarrayOfOneOfsRequest + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + + public APIarrayOfOneOfsRequest arrayOfOneOfs() { + return new APIarrayOfOneOfsRequest(); + } private okhttp3.Call arrayRequestParametersCall(List myStringArrayRequestParams, List myEnumArrayRequestParams, List myIntegerArrayRequestParams, List myLongArrayRequestParams, List myInt32ArrayRequestParams, List myNumberArrayRequestParams, List myFloatArrayRequestParams, List myDoubleArrayRequestParams, MyEnum myEnumRequestParam, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers @@ -33481,6 +33661,151 @@ public class DefaultApi { public APIarrayRequestParametersRequest arrayRequestParameters() { return new APIarrayRequestParametersRequest(); } + private okhttp3.Call dictionaryCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/additional-properties"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + + @SuppressWarnings("rawtypes") + private okhttp3.Call dictionaryValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return dictionaryCall(_callback); + + } + + private ApiResponse dictionaryWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = dictionaryValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + + private okhttp3.Call dictionaryAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = dictionaryValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIdictionaryRequest { + + private APIdictionaryRequest() { + } + + /** + * Build call for dictionary + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return dictionaryCall(_callback); + } + + /** + * Execute dictionary request + * @return AdditionalPropertiesResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public AdditionalPropertiesResponse execute() throws ApiException { + ApiResponse localVarResp = dictionaryWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Execute dictionary request with HTTP info returned + * @return ApiResponse<AdditionalPropertiesResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return dictionaryWithHttpInfo(); + } + + /** + * Execute dictionary request (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 + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return dictionaryAsync(_callback); + } + } + + /** + * + * + * @return APIdictionaryRequest + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + + public APIdictionaryRequest dictionary() { + return new APIdictionaryRequest(); + } private okhttp3.Call inlineEnumCall(final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers @@ -33778,7 +34103,7 @@ public class DefaultApi { public APIinlineRequestBodyRequest inlineRequestBody() { return new APIinlineRequestBodyRequest(); } - private okhttp3.Call reservedKeywordsCall(String with, String _if, String propertyClass, final ApiCallback _callback) throws ApiException { + private okhttp3.Call namedOneOfCall(final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -33795,7 +34120,7 @@ public class DefaultApi { Object localVarPostBody = null; // create path and map variables - String localVarPath = "/reserved-keywords"; + String localVarPath = "/named-one-of"; List localVarQueryParams = new ArrayList(); List localVarCollectionQueryParams = new ArrayList(); @@ -33803,19 +34128,8 @@ public class DefaultApi { Map localVarCookieParams = new HashMap(); Map localVarFormParams = new HashMap(); - if (with != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("with", with)); - } - - if (_if != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("if", _if)); - } - - if (propertyClass != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("class", propertyClass)); - } - final String[] localVarAccepts = { + "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { @@ -33830,19 +34144,175 @@ public class DefaultApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") - private okhttp3.Call reservedKeywordsValidateBeforeCall(String with, String _if, String propertyClass, final ApiCallback _callback) throws ApiException { - return reservedKeywordsCall(with, _if, propertyClass, _callback); + private okhttp3.Call namedOneOfValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return namedOneOfCall(_callback); } - private ApiResponse reservedKeywordsWithHttpInfo(String with, String _if, String propertyClass) throws ApiException { - okhttp3.Call localVarCall = reservedKeywordsValidateBeforeCall(with, _if, propertyClass, null); - return localVarApiClient.execute(localVarCall); + private ApiResponse namedOneOfWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = namedOneOfValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + + private okhttp3.Call namedOneOfAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = namedOneOfValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APInamedOneOfRequest { + + private APInamedOneOfRequest() { + } + + /** + * Build call for namedOneOf + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return namedOneOfCall(_callback); + } + + /** + * Execute namedOneOf request + * @return NamedOneOfUnion + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public NamedOneOfUnion execute() throws ApiException { + ApiResponse localVarResp = namedOneOfWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Execute namedOneOf request with HTTP info returned + * @return ApiResponse<NamedOneOfUnion> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return namedOneOfWithHttpInfo(); + } + + /** + * Execute namedOneOf request (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 + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return namedOneOfAsync(_callback); + } + } + + /** + * + * + * @return APInamedOneOfRequest + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + + public APInamedOneOfRequest namedOneOf() { + return new APInamedOneOfRequest(); + } + private okhttp3.Call reservedKeywordsCall(String with, String _if, String propertyClass, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/reserved-keywords"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (with != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("with", with)); + } + + if (_if != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("if", _if)); + } + + if (propertyClass != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("class", propertyClass)); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + + @SuppressWarnings("rawtypes") + private okhttp3.Call reservedKeywordsValidateBeforeCall(String with, String _if, String propertyClass, final ApiCallback _callback) throws ApiException { + return reservedKeywordsCall(with, _if, propertyClass, _callback); + + } + + private ApiResponse reservedKeywordsWithHttpInfo(String with, String _if, String propertyClass) throws ApiException { + okhttp3.Call localVarCall = reservedKeywordsValidateBeforeCall(with, _if, propertyClass, null); + return localVarApiClient.execute(localVarCall); } @@ -34011,9 +34481,12 @@ public interface HandlerChain { "src/main/java/test/test/runtime/api/handlers/HandlerRouter.java": " package test.test.runtime.api.handlers; +import test.test.runtime.api.handlers.array_of_one_ofs.*; import test.test.runtime.api.handlers.array_request_parameters.*; +import test.test.runtime.api.handlers.dictionary.*; import test.test.runtime.api.handlers.inline_enum.*; import test.test.runtime.api.handlers.inline_request_body.*; +import test.test.runtime.api.handlers.named_one_of.*; import test.test.runtime.api.handlers.reserved_keywords.*; import test.test.runtime.api.handlers.Handlers; @@ -34032,20 +34505,34 @@ import java.util.Collections; public abstract class HandlerRouter implements RequestHandler { + private static final String arrayOfOneOfsMethodAndPath = Handlers.concatMethodAndPath("POST", "/array-of-one-ofs"); private static final String arrayRequestParametersMethodAndPath = Handlers.concatMethodAndPath("GET", "/array-request-parameters"); + private static final String dictionaryMethodAndPath = Handlers.concatMethodAndPath("POST", "/additional-properties"); private static final String inlineEnumMethodAndPath = Handlers.concatMethodAndPath("GET", "/inline-enum"); private static final String inlineRequestBodyMethodAndPath = Handlers.concatMethodAndPath("POST", "/inline-request-body"); + private static final String namedOneOfMethodAndPath = Handlers.concatMethodAndPath("POST", "/named-one-of"); private static final String reservedKeywordsMethodAndPath = Handlers.concatMethodAndPath("GET", "/reserved-keywords"); + private final ArrayOfOneOfs constructedArrayOfOneOfs; private final ArrayRequestParameters constructedArrayRequestParameters; + private final Dictionary constructedDictionary; private final InlineEnum constructedInlineEnum; private final InlineRequestBody constructedInlineRequestBody; + private final NamedOneOf constructedNamedOneOf; private final ReservedKeywords constructedReservedKeywords; + /** + * This method must return your implementation of the ArrayOfOneOfs operation + */ + public abstract ArrayOfOneOfs arrayOfOneOfs(); /** * This method must return your implementation of the ArrayRequestParameters operation */ public abstract ArrayRequestParameters arrayRequestParameters(); + /** + * This method must return your implementation of the Dictionary operation + */ + public abstract Dictionary dictionary(); /** * This method must return your implementation of the InlineEnum operation */ @@ -34054,15 +34541,22 @@ public abstract class HandlerRouter implements RequestHandler routes = new HashMap<>(); public HandlerRouter() { + this.routes.put(arrayOfOneOfsMethodAndPath, Route.arrayOfOneOfsRoute); this.routes.put(arrayRequestParametersMethodAndPath, Route.arrayRequestParametersRoute); + this.routes.put(dictionaryMethodAndPath, Route.dictionaryRoute); this.routes.put(inlineEnumMethodAndPath, Route.inlineEnumRoute); this.routes.put(inlineRequestBodyMethodAndPath, Route.inlineRequestBodyRoute); + this.routes.put(namedOneOfMethodAndPath, Route.namedOneOfRoute); this.routes.put(reservedKeywordsMethodAndPath, Route.reservedKeywordsRoute); // Handlers are all constructed in the router's constructor such that lambda behaviour remains consistent; // ie resources created in the constructor remain in memory between invocations. // https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html + this.constructedArrayOfOneOfs = this.arrayOfOneOfs(); this.constructedArrayRequestParameters = this.arrayRequestParameters(); + this.constructedDictionary = this.dictionary(); this.constructedInlineEnum = this.inlineEnum(); this.constructedInlineRequestBody = this.inlineRequestBody(); + this.constructedNamedOneOf = this.namedOneOf(); this.constructedReservedKeywords = this.reservedKeywords(); } @@ -34102,10 +34602,18 @@ public abstract class HandlerRouter implements RequestHandler> arrayOfOneOfsInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + arrayOfOneOfsInterceptors.addAll(this.getInterceptors()); + return this.constructedArrayOfOneOfs.handleRequestWithAdditionalInterceptors(event, context, arrayOfOneOfsInterceptors); case arrayRequestParametersRoute: List> arrayRequestParametersInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); arrayRequestParametersInterceptors.addAll(this.getInterceptors()); return this.constructedArrayRequestParameters.handleRequestWithAdditionalInterceptors(event, context, arrayRequestParametersInterceptors); + case dictionaryRoute: + List> dictionaryInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + dictionaryInterceptors.addAll(this.getInterceptors()); + return this.constructedDictionary.handleRequestWithAdditionalInterceptors(event, context, dictionaryInterceptors); case inlineEnumRoute: List> inlineEnumInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); inlineEnumInterceptors.addAll(this.getInterceptors()); @@ -34114,6 +34622,10 @@ public abstract class HandlerRouter implements RequestHandler> inlineRequestBodyInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); inlineRequestBodyInterceptors.addAll(this.getInterceptors()); return this.constructedInlineRequestBody.handleRequestWithAdditionalInterceptors(event, context, inlineRequestBodyInterceptors); + case namedOneOfRoute: + List> namedOneOfInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + namedOneOfInterceptors.addAll(this.getInterceptors()); + return this.constructedNamedOneOf.handleRequestWithAdditionalInterceptors(event, context, namedOneOfInterceptors); case reservedKeywordsRoute: List> reservedKeywordsInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); reservedKeywordsInterceptors.addAll(this.getInterceptors()); @@ -34780,8 +35292,8 @@ public interface Response { Map> getMultiValueHeaders(); } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -34805,50 +35317,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the arrayRequestParameters operation + * Lambda handler wrapper for the arrayOfOneOfs operation */ -public abstract class ArrayRequestParameters implements RequestHandler, Resource { +public abstract class ArrayOfOneOfs implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the arrayRequestParameters operation + * Handle the request for the arrayOfOneOfs operation */ - public abstract ArrayRequestParametersResponse handle(final ArrayRequestParametersRequestInput request); + public abstract ArrayOfOneOfsResponse handle(final ArrayOfOneOfsRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ArrayRequestParameters.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ArrayOfOneOfs.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new ArrayRequestParametersRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new ArrayOfOneOfsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ArrayRequestParametersInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ArrayOfOneOfsInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -34867,7 +35379,7 @@ public abstract class ArrayRequestParameters implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -34928,20 +35440,20 @@ public abstract class ArrayRequestParameters implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "arrayRequestParameters"); + interceptorContext.put("operationId", "arrayOfOneOfs"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - ArrayRequestParametersInput input; + ArrayOfOneOfsInput input; try { - input = new ArrayRequestParametersInput(event); + input = new ArrayOfOneOfsInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -34966,8 +35478,8 @@ public abstract class ArrayRequestParameters implements RequestHandler headers; private final Map> multiValueHeaders; - private ArrayRequestParameters200Response(final Map headers, final Map> multiValueHeaders) { - - this.body = ""; + private ArrayOfOneOfs200Response(final ArrayOfOneOfs body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @@ -35009,6 +35521,9 @@ public class ArrayRequestParameters200Response extends RuntimeException implemen return this.body; } + public ArrayOfOneOfs getTypedBody() { + return this.typedBody; + } @Override public Map getHeaders() { @@ -35021,29 +35536,29 @@ public class ArrayRequestParameters200Response extends RuntimeException implemen } /** - * Create a ArrayRequestParameters200Response without a body + * Create a ArrayOfOneOfs200Response with a body */ - public static ArrayRequestParameters200Response of() { - return new ArrayRequestParameters200Response(new HashMap<>(), new HashMap<>()); + public static ArrayOfOneOfs200Response of(final ArrayOfOneOfs body) { + return new ArrayOfOneOfs200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a ArrayRequestParameters200Response without a body and headers + * Create a ArrayOfOneOfs200Response with a body and headers */ - public static ArrayRequestParameters200Response of(final Map headers) { - return new ArrayRequestParameters200Response(headers, new HashMap<>()); + public static ArrayOfOneOfs200Response of(final ArrayOfOneOfs body, final Map headers) { + return new ArrayOfOneOfs200Response(body, headers, new HashMap<>()); } /** - * Create a ArrayRequestParameters200Response without a body, headers and multi-value headers + * Create a ArrayOfOneOfs200Response with a body, headers and multi-value headers */ - public static ArrayRequestParameters200Response of(final Map headers, final Map> multiValueHeaders) { - return new ArrayRequestParameters200Response(headers, multiValueHeaders); + public static ArrayOfOneOfs200Response of(final ArrayOfOneOfs body, final Map headers, final Map> multiValueHeaders) { + return new ArrayOfOneOfs200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersInput.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsInput.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35056,11 +35571,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the arrayRequestParameters operation + * Input for the arrayOfOneOfs operation */ @lombok.Builder @lombok.AllArgsConstructor -public class ArrayRequestParametersInput { +public class ArrayOfOneOfsInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -35069,20 +35584,20 @@ public class ArrayRequestParametersInput { } } - private final ArrayRequestParametersRequestParameters requestParameters; + private final ArrayOfOneOfsRequestParameters requestParameters; - public ArrayRequestParametersInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new ArrayRequestParametersRequestParameters(event); + public ArrayOfOneOfsInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new ArrayOfOneOfsRequestParameters(event); } - public ArrayRequestParametersRequestParameters getRequestParameters() { + public ArrayOfOneOfsRequestParameters getRequestParameters() { return this.requestParameters; } } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestInput.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestInput.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -35095,20 +35610,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the arrayRequestParameters operation, including the raw API Gateway event + * Full request input for the arrayOfOneOfs operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class ArrayRequestParametersRequestInput implements RequestInput { +public class ArrayOfOneOfsRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final ArrayRequestParametersInput input; + private final ArrayOfOneOfsInput input; /** * Returns the typed request input, with path, query and body parameters */ - public ArrayRequestParametersInput getInput() { + public ArrayOfOneOfsInput getInput() { return this.input; } @@ -35134,8 +35649,8 @@ public class ArrayRequestParametersRequestInput implements RequestInput> myStringArrayRequestParams; - private final Optional> myEnumArrayRequestParams; - private final Optional> myIntegerArrayRequestParams; - private final Optional> myLongArrayRequestParams; - private final Optional> myInt32ArrayRequestParams; - private final Optional> myNumberArrayRequestParams; - private final Optional> myFloatArrayRequestParams; - private final Optional> myDoubleArrayRequestParams; - private final Optional myEnumRequestParam; +public class ArrayOfOneOfsRequestParameters { - public ArrayRequestParametersRequestParameters(final APIGatewayProxyRequestEvent event) { + public ArrayOfOneOfsRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -35179,59 +35685,23 @@ public class ArrayRequestParametersRequestParameters { Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); - this.myStringArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-string-array-request-params", false, decodedStringArrayParameters)); - this.myEnumArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-enum-array-request-params", false, decodedStringArrayParameters).stream().map(MyEnum::fromValue).collect(Collectors.toList())); - this.myIntegerArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-integer-array-request-params", false, decodedStringArrayParameters)); - this.myLongArrayRequestParams = Optional.ofNullable(Handlers.coerceLongArrayParameter("my-long-array-request-params", false, decodedStringArrayParameters)); - this.myInt32ArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-int32-array-request-params", false, decodedStringArrayParameters)); - this.myNumberArrayRequestParams = Optional.ofNullable(Handlers.coerceBigDecimalArrayParameter("my-number-array-request-params", false, decodedStringArrayParameters)); - this.myFloatArrayRequestParams = Optional.ofNullable(Handlers.coerceFloatArrayParameter("my-float-array-request-params", false, decodedStringArrayParameters)); - this.myDoubleArrayRequestParams = Optional.ofNullable(Handlers.coerceDoubleArrayParameter("my-double-array-request-params", false, decodedStringArrayParameters)); - this.myEnumRequestParam = Optional.ofNullable(MyEnum.fromValue(Handlers.coerceStringParameter("my-enum-request-param", false, decodedStringParameters))); } - public Optional> getMyStringArrayRequestParams() { - return this.myStringArrayRequestParams; - } - public Optional> getMyEnumArrayRequestParams() { - return this.myEnumArrayRequestParams; - } - public Optional> getMyIntegerArrayRequestParams() { - return this.myIntegerArrayRequestParams; - } - public Optional> getMyLongArrayRequestParams() { - return this.myLongArrayRequestParams; - } - public Optional> getMyInt32ArrayRequestParams() { - return this.myInt32ArrayRequestParams; - } - public Optional> getMyNumberArrayRequestParams() { - return this.myNumberArrayRequestParams; - } - public Optional> getMyFloatArrayRequestParams() { - return this.myFloatArrayRequestParams; - } - public Optional> getMyDoubleArrayRequestParams() { - return this.myDoubleArrayRequestParams; - } - public Optional getMyEnumRequestParam() { - return this.myEnumRequestParam; - } } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersResponse.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsResponse.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.api.handlers.Response; /** - * Response for the arrayRequestParameters operation + * Response for the arrayOfOneOfs operation */ -public interface ArrayRequestParametersResponse extends Response {} +public interface ArrayOfOneOfsResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java": " -package test.test.runtime.api.handlers.inline_enum; - + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters.java": " +package test.test.runtime.api.handlers.array_request_parameters; + import test.test.runtime.model.*; import test.test.runtime.JSON; import test.test.runtime.api.handlers.Interceptor; @@ -35254,50 +35724,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the inlineEnum operation + * Lambda handler wrapper for the arrayRequestParameters operation */ -public abstract class InlineEnum implements RequestHandler, Resource { +public abstract class ArrayRequestParameters implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the inlineEnum operation + * Handle the request for the arrayRequestParameters operation */ - public abstract InlineEnumResponse handle(final InlineEnumRequestInput request); + public abstract ArrayRequestParametersResponse handle(final ArrayRequestParametersRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineEnum.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ArrayRequestParameters.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new InlineEnumRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new ArrayRequestParametersRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineEnumInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ArrayRequestParametersInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -35316,7 +35786,7 @@ public abstract class InlineEnum implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -35377,20 +35847,20 @@ public abstract class InlineEnum implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "inlineEnum"); + interceptorContext.put("operationId", "arrayRequestParameters"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - InlineEnumInput input; + ArrayRequestParametersInput input; try { - input = new InlineEnumInput(event); + input = new ArrayRequestParametersInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -35415,8 +35885,8 @@ public abstract class InlineEnum implements RequestHandler headers; private final Map> multiValueHeaders; - private InlineEnum200Response(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { - this.typedBody = body; - this.body = body.toJson(); + private ArrayRequestParameters200Response(final Map headers, final Map> multiValueHeaders) { + + this.body = ""; this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @@ -35458,9 +35928,6 @@ public class InlineEnum200Response extends RuntimeException implements InlineEnu return this.body; } - public InlineEnum200Response getTypedBody() { - return this.typedBody; - } @Override public Map getHeaders() { @@ -35473,29 +35940,29 @@ public class InlineEnum200Response extends RuntimeException implements InlineEnu } /** - * Create a InlineEnum200Response with a body + * Create a ArrayRequestParameters200Response without a body */ - public static InlineEnum200Response of(final InlineEnum200Response body) { - return new InlineEnum200Response(body, new HashMap<>(), new HashMap<>()); + public static ArrayRequestParameters200Response of() { + return new ArrayRequestParameters200Response(new HashMap<>(), new HashMap<>()); } /** - * Create a InlineEnum200Response with a body and headers + * Create a ArrayRequestParameters200Response without a body and headers */ - public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers) { - return new InlineEnum200Response(body, headers, new HashMap<>()); + public static ArrayRequestParameters200Response of(final Map headers) { + return new ArrayRequestParameters200Response(headers, new HashMap<>()); } /** - * Create a InlineEnum200Response with a body, headers and multi-value headers + * Create a ArrayRequestParameters200Response without a body, headers and multi-value headers */ - public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { - return new InlineEnum200Response(body, headers, multiValueHeaders); + public static ArrayRequestParameters200Response of(final Map headers, final Map> multiValueHeaders) { + return new ArrayRequestParameters200Response(headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersInput.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35508,11 +35975,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the inlineEnum operation + * Input for the arrayRequestParameters operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumInput { +public class ArrayRequestParametersInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -35521,20 +35988,20 @@ public class InlineEnumInput { } } - private final InlineEnumRequestParameters requestParameters; + private final ArrayRequestParametersRequestParameters requestParameters; - public InlineEnumInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new InlineEnumRequestParameters(event); + public ArrayRequestParametersInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new ArrayRequestParametersRequestParameters(event); } - public InlineEnumRequestParameters getRequestParameters() { + public ArrayRequestParametersRequestParameters getRequestParameters() { return this.requestParameters; } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestInput.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -35547,20 +36014,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the inlineEnum operation, including the raw API Gateway event + * Full request input for the arrayRequestParameters operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumRequestInput implements RequestInput { +public class ArrayRequestParametersRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final InlineEnumInput input; + private final ArrayRequestParametersInput input; /** * Returns the typed request input, with path, query and body parameters */ - public InlineEnumInput getInput() { + public ArrayRequestParametersInput getInput() { return this.input; } @@ -35586,8 +36053,8 @@ public class InlineEnumRequestInput implements RequestInput { } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestParameters.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestParameters.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.api.handlers.Handlers; import java.util.Optional; @@ -35604,13 +36071,22 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import test.test.runtime.model.*; /** - * Query, path and header parameters for the InlineEnum operation + * Query, path and header parameters for the ArrayRequestParameters operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumRequestParameters { +public class ArrayRequestParametersRequestParameters { + private final Optional> myStringArrayRequestParams; + private final Optional> myEnumArrayRequestParams; + private final Optional> myIntegerArrayRequestParams; + private final Optional> myLongArrayRequestParams; + private final Optional> myInt32ArrayRequestParams; + private final Optional> myNumberArrayRequestParams; + private final Optional> myFloatArrayRequestParams; + private final Optional> myDoubleArrayRequestParams; + private final Optional myEnumRequestParam; - public InlineEnumRequestParameters(final APIGatewayProxyRequestEvent event) { + public ArrayRequestParametersRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -35622,22 +36098,58 @@ public class InlineEnumRequestParameters { Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); + this.myStringArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-string-array-request-params", false, decodedStringArrayParameters)); + this.myEnumArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-enum-array-request-params", false, decodedStringArrayParameters).stream().map(MyEnum::fromValue).collect(Collectors.toList())); + this.myIntegerArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-integer-array-request-params", false, decodedStringArrayParameters)); + this.myLongArrayRequestParams = Optional.ofNullable(Handlers.coerceLongArrayParameter("my-long-array-request-params", false, decodedStringArrayParameters)); + this.myInt32ArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-int32-array-request-params", false, decodedStringArrayParameters)); + this.myNumberArrayRequestParams = Optional.ofNullable(Handlers.coerceBigDecimalArrayParameter("my-number-array-request-params", false, decodedStringArrayParameters)); + this.myFloatArrayRequestParams = Optional.ofNullable(Handlers.coerceFloatArrayParameter("my-float-array-request-params", false, decodedStringArrayParameters)); + this.myDoubleArrayRequestParams = Optional.ofNullable(Handlers.coerceDoubleArrayParameter("my-double-array-request-params", false, decodedStringArrayParameters)); + this.myEnumRequestParam = Optional.ofNullable(MyEnum.fromValue(Handlers.coerceStringParameter("my-enum-request-param", false, decodedStringParameters))); } + public Optional> getMyStringArrayRequestParams() { + return this.myStringArrayRequestParams; + } + public Optional> getMyEnumArrayRequestParams() { + return this.myEnumArrayRequestParams; + } + public Optional> getMyIntegerArrayRequestParams() { + return this.myIntegerArrayRequestParams; + } + public Optional> getMyLongArrayRequestParams() { + return this.myLongArrayRequestParams; + } + public Optional> getMyInt32ArrayRequestParams() { + return this.myInt32ArrayRequestParams; + } + public Optional> getMyNumberArrayRequestParams() { + return this.myNumberArrayRequestParams; + } + public Optional> getMyFloatArrayRequestParams() { + return this.myFloatArrayRequestParams; + } + public Optional> getMyDoubleArrayRequestParams() { + return this.myDoubleArrayRequestParams; + } + public Optional getMyEnumRequestParam() { + return this.myEnumRequestParam; + } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersResponse.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.api.handlers.Response; /** - * Response for the inlineEnum operation + * Response for the arrayRequestParameters operation */ -public interface InlineEnumResponse extends Response {} +public interface ArrayRequestParametersResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/dictionary/Dictionary.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35661,50 +36173,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the inlineRequestBody operation + * Lambda handler wrapper for the dictionary operation */ -public abstract class InlineRequestBody implements RequestHandler, Resource { +public abstract class Dictionary implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the inlineRequestBody operation + * Handle the request for the dictionary operation */ - public abstract InlineRequestBodyResponse handle(final InlineRequestBodyRequestInput request); + public abstract DictionaryResponse handle(final DictionaryRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineRequestBody.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(Dictionary.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new InlineRequestBodyRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new DictionaryRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineRequestBodyInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final DictionaryInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -35723,7 +36235,7 @@ public abstract class InlineRequestBody implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -35784,20 +36296,20 @@ public abstract class InlineRequestBody implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "inlineRequestBody"); + interceptorContext.put("operationId", "dictionary"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - InlineRequestBodyInput input; + DictionaryInput input; try { - input = new InlineRequestBodyInput(event); + input = new DictionaryInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -35822,8 +36334,8 @@ public abstract class InlineRequestBody implements RequestHandler headers; private final Map> multiValueHeaders; - private InlineRequestBody204Response(final Map headers, final Map> multiValueHeaders) { - - this.body = ""; + private Dictionary200Response(final AdditionalPropertiesResponse body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @Override public int getStatusCode() { - return 204; + return 200; } @Override @@ -35865,6 +36377,9 @@ public class InlineRequestBody204Response extends RuntimeException implements In return this.body; } + public AdditionalPropertiesResponse getTypedBody() { + return this.typedBody; + } @Override public Map getHeaders() { @@ -35877,29 +36392,29 @@ public class InlineRequestBody204Response extends RuntimeException implements In } /** - * Create a InlineRequestBody204Response without a body + * Create a Dictionary200Response with a body */ - public static InlineRequestBody204Response of() { - return new InlineRequestBody204Response(new HashMap<>(), new HashMap<>()); + public static Dictionary200Response of(final AdditionalPropertiesResponse body) { + return new Dictionary200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a InlineRequestBody204Response without a body and headers + * Create a Dictionary200Response with a body and headers */ - public static InlineRequestBody204Response of(final Map headers) { - return new InlineRequestBody204Response(headers, new HashMap<>()); + public static Dictionary200Response of(final AdditionalPropertiesResponse body, final Map headers) { + return new Dictionary200Response(body, headers, new HashMap<>()); } /** - * Create a InlineRequestBody204Response without a body, headers and multi-value headers + * Create a Dictionary200Response with a body, headers and multi-value headers */ - public static InlineRequestBody204Response of(final Map headers, final Map> multiValueHeaders) { - return new InlineRequestBody204Response(headers, multiValueHeaders); + public static Dictionary200Response of(final AdditionalPropertiesResponse body, final Map headers, final Map> multiValueHeaders) { + return new Dictionary200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryInput.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35912,11 +36427,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the inlineRequestBody operation + * Input for the dictionary operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineRequestBodyInput { +public class DictionaryInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -35925,29 +36440,20 @@ public class InlineRequestBodyInput { } } - private final InlineRequestBodyRequestParameters requestParameters; - private final InlineRequestBodyRequestContent body; + private final DictionaryRequestParameters requestParameters; - public InlineRequestBodyInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new InlineRequestBodyRequestParameters(event); - try { - this.body = InlineRequestBodyRequestContent.fromJson(event.getBody()); - } catch (IOException e) { - throw new RuntimeException(e); - }; + public DictionaryInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new DictionaryRequestParameters(event); } - public InlineRequestBodyRequestParameters getRequestParameters() { + public DictionaryRequestParameters getRequestParameters() { return this.requestParameters; } - public InlineRequestBodyRequestContent getBody() { - return this.body; - } } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryRequestInput.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -35960,20 +36466,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the inlineRequestBody operation, including the raw API Gateway event + * Full request input for the dictionary operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineRequestBodyRequestInput implements RequestInput { +public class DictionaryRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final InlineRequestBodyInput input; + private final DictionaryInput input; /** * Returns the typed request input, with path, query and body parameters */ - public InlineRequestBodyInput getInput() { + public DictionaryInput getInput() { return this.input; } @@ -35999,8 +36505,8 @@ public class InlineRequestBodyRequestInput implements RequestInput rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -36039,18 +36545,18 @@ public class InlineRequestBodyRequestParameters { } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryResponse.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.api.handlers.Response; /** - * Response for the inlineRequestBody operation + * Response for the dictionary operation */ -public interface InlineRequestBodyResponse extends Response {} +public interface DictionaryResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36074,50 +36580,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the reservedKeywords operation + * Lambda handler wrapper for the inlineEnum operation */ -public abstract class ReservedKeywords implements RequestHandler, Resource { +public abstract class InlineEnum implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the reservedKeywords operation + * Handle the request for the inlineEnum operation */ - public abstract ReservedKeywordsResponse handle(final ReservedKeywordsRequestInput request); + public abstract InlineEnumResponse handle(final InlineEnumRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ReservedKeywords.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineEnum.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new ReservedKeywordsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new InlineEnumRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ReservedKeywordsInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineEnumInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -36136,7 +36642,7 @@ public abstract class ReservedKeywords implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -36197,20 +36703,20 @@ public abstract class ReservedKeywords implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "reservedKeywords"); + interceptorContext.put("operationId", "inlineEnum"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - ReservedKeywordsInput input; + InlineEnumInput input; try { - input = new ReservedKeywordsInput(event); + input = new InlineEnumInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -36235,8 +36741,8 @@ public abstract class ReservedKeywords implements RequestHandler headers; private final Map> multiValueHeaders; - private ReservedKeywords200Response(final Map headers, final Map> multiValueHeaders) { - - this.body = ""; + private InlineEnum200Response(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @@ -36278,6 +36784,9 @@ public class ReservedKeywords200Response extends RuntimeException implements Res return this.body; } + public InlineEnum200Response getTypedBody() { + return this.typedBody; + } @Override public Map getHeaders() { @@ -36290,29 +36799,29 @@ public class ReservedKeywords200Response extends RuntimeException implements Res } /** - * Create a ReservedKeywords200Response without a body + * Create a InlineEnum200Response with a body */ - public static ReservedKeywords200Response of() { - return new ReservedKeywords200Response(new HashMap<>(), new HashMap<>()); + public static InlineEnum200Response of(final InlineEnum200Response body) { + return new InlineEnum200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a ReservedKeywords200Response without a body and headers + * Create a InlineEnum200Response with a body and headers */ - public static ReservedKeywords200Response of(final Map headers) { - return new ReservedKeywords200Response(headers, new HashMap<>()); + public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers) { + return new InlineEnum200Response(body, headers, new HashMap<>()); } /** - * Create a ReservedKeywords200Response without a body, headers and multi-value headers + * Create a InlineEnum200Response with a body, headers and multi-value headers */ - public static ReservedKeywords200Response of(final Map headers, final Map> multiValueHeaders) { - return new ReservedKeywords200Response(headers, multiValueHeaders); + public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { + return new InlineEnum200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsInput.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36325,11 +36834,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the reservedKeywords operation + * Input for the inlineEnum operation */ @lombok.Builder @lombok.AllArgsConstructor -public class ReservedKeywordsInput { +public class InlineEnumInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -36338,20 +36847,20 @@ public class ReservedKeywordsInput { } } - private final ReservedKeywordsRequestParameters requestParameters; + private final InlineEnumRequestParameters requestParameters; - public ReservedKeywordsInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new ReservedKeywordsRequestParameters(event); + public InlineEnumInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new InlineEnumRequestParameters(event); } - public ReservedKeywordsRequestParameters getRequestParameters() { + public InlineEnumRequestParameters getRequestParameters() { return this.requestParameters; } } ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestInput.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -36364,20 +36873,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the reservedKeywords operation, including the raw API Gateway event + * Full request input for the inlineEnum operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class ReservedKeywordsRequestInput implements RequestInput { +public class InlineEnumRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final ReservedKeywordsInput input; + private final InlineEnumInput input; /** * Returns the typed request input, with path, query and body parameters */ - public ReservedKeywordsInput getInput() { + public InlineEnumInput getInput() { return this.input; } @@ -36403,8 +36912,8 @@ public class ReservedKeywordsRequestInput implements RequestInput with; - private final Optional _if; - private final Optional propertyClass; +public class InlineEnumRequestParameters { - public ReservedKeywordsRequestParameters(final APIGatewayProxyRequestEvent event) { + public InlineEnumRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -36442,467 +36948,3021 @@ public class ReservedKeywordsRequestParameters { Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); - this.with = Optional.ofNullable(Handlers.coerceStringParameter("with", false, decodedStringParameters)); - this._if = Optional.ofNullable(Handlers.coerceStringParameter("if", false, decodedStringParameters)); - this.propertyClass = Optional.ofNullable(Handlers.coerceStringParameter("class", false, decodedStringParameters)); } - public Optional getWith() { - return this.with; - } - public Optional getIf() { - return this._if; - } - public Optional getPropertyClass() { - return this.propertyClass; - } } ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsResponse.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.api.handlers.Response; /** - * Response for the reservedKeywords operation + * Response for the inlineEnum operation */ -public interface ReservedKeywordsResponse extends Response {} +public interface InlineEnumResponse extends Response {} ", - "src/main/java/test/test/runtime/api/interceptors/DefaultInterceptors.java": "package test.test.runtime.api.interceptors; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java": " +package test.test.runtime.api.handlers.inline_request_body; -import test.test.runtime.api.interceptors.powertools.LoggingInterceptor; -import test.test.runtime.api.interceptors.powertools.MetricsInterceptor; -import test.test.runtime.api.interceptors.powertools.TracingInterceptor; +import test.test.runtime.model.*; +import test.test.runtime.JSON; import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; -import java.util.Arrays; import java.util.List; - -public class DefaultInterceptors { - public static List> all() { - return Arrays.asList( - new ResponseHeadersInterceptor<>(), - new LoggingInterceptor<>(), - new TryCatchInterceptor<>(), - new TracingInterceptor<>(), - new MetricsInterceptor<>() - ); - } -}", - "src/main/java/test/test/runtime/api/interceptors/ResponseHeadersInterceptor.java": "package test.test.runtime.api.interceptors; - -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; +import java.util.ArrayList; +import java.util.Optional; import java.util.Map; import java.util.HashMap; +import java.util.Collections; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import org.crac.Core; +import org.crac.Resource; + /** - * An interceptor for adding cross-origin resource sharing (CORS) headers to the response. - * Allows all origins and headers. + * Lambda handler wrapper for the inlineRequestBody operation */ -public class ResponseHeadersInterceptor extends InterceptorWithWarmup { - private final Map additionalHeaders; - - public ResponseHeadersInterceptor() { - this.additionalHeaders = new HashMap<>(); - this.additionalHeaders.put("Access-Control-Allow-Origin", "*"); - this.additionalHeaders.put("Access-Control-Allow-Headers", "*"); +public abstract class InlineRequestBody implements RequestHandler, Resource { + { + Core.getGlobalContext().register(this); } - public ResponseHeadersInterceptor(final Map headers) { - this.additionalHeaders = headers; - } + /** + * Handle the request for the inlineRequestBody operation + */ + public abstract InlineRequestBodyResponse handle(final InlineRequestBodyRequestInput request); - @Override - public Response handle(ChainedRequestInput input) { - Response res = input.getChain().next(input); - res.getHeaders().putAll(this.additionalHeaders); - return res; - } + /** + * Interceptors that the handler class has been decorated with + */ + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineRequestBody.class); - public Map getAdditionalHeaders() { - return this.additionalHeaders; + /** + * For more complex interceptors that require instantiation with parameters, you may override this method to + * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, + * prefer the @Interceptors annotation. + */ + public List> getInterceptors() { + return Collections.emptyList(); } -} -", - "src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java": "package test.test.runtime.api.interceptors; - -import test.test.runtime.api.handlers.ApiResponse; -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import org.apache.logging.log4j.Logger; - -/** - * Interceptor for handling uncaught exceptions and responding with a default error response - */ -public class TryCatchInterceptor extends InterceptorWithWarmup { - private final int statusCode; - private final String errorResponseBody; - public TryCatchInterceptor() { - this(500, "{\\"message\\": \\"Internal Error\\"}"); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); + interceptors.addAll(annotationInterceptors); + interceptors.addAll(this.getInterceptors()); + return interceptors; } - public TryCatchInterceptor(final int statusCode, final String errorResponseBody) { - this.statusCode = statusCode; - this.errorResponseBody = errorResponseBody; + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return handle(new InlineRequestBodyRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + } + }); } - @Override - public Response handle(final ChainedRequestInput input) { - try { - return input.getChain().next(input); - } catch (Throwable e) { - if (e instanceof Response) { - return (Response) e; + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineRequestBodyInput input, final Map interceptorContext) { + return new ChainedRequestInput() { + @Override + public HandlerChain getChain() { + // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining + // chain. + return null; } - Object logger = input.getInterceptorContext().get("logger"); - if (logger instanceof Logger) { - ((Logger) logger).error("Interceptor caught exception", e); - } else { - System.err.println("Interceptor caught exception"); - e.printStackTrace(); + @Override + public APIGatewayProxyRequestEvent getEvent() { + return event; } - return ApiResponse.builder() - .statusCode(this.statusCode) - .body(this.errorResponseBody) - .build(); - } + @Override + public Context getContext() { + return context; + } + + @Override + public InlineRequestBodyInput getInput() { + return input; + } + + @Override + public Map getInterceptorContext() { + return interceptorContext; + } + }; } -} -", - "src/main/java/test/test/runtime/api/interceptors/powertools/LoggingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.RequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import com.amazonaws.services.lambda.runtime.Context; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.ThreadContext; -import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; -import software.amazon.lambda.powertools.logging.LoggingUtils; + @Override + public void beforeCheckpoint(org.crac.Context context) { + // Prime building the handler chain which can take a few 100ms to JIT. + this.buildChain(this.getHandlerInterceptors()); + this.buildChainedRequestInput(null, null, null, null); -/** - * An interceptor which adds an aws lambda powertools logger to the interceptor context, - * and adds the lambda context. - * See https://docs.powertools.aws.dev/lambda/java/latest/core/logging/ - */ -public class LoggingInterceptor extends InterceptorWithWarmup { - private Logger logger = LogManager.getLogger(LoggingInterceptor.class); + // Initialise instance of Gson and prime serialisation and deserialisation + new JSON(); + JSON.getGson().fromJson(JSON.getGson().toJson(new ApiResponse("", 0, new HashMap<>(), new HashMap<>())), ApiResponse.class); + + try { + // Prime input validation - this will likely fail for the fake event but ensures the code path is optimised + // ready for a real invocation + new InlineRequestBodyInput(new APIGatewayProxyRequestEvent() + .withBody("{}") + .withPathParameters(new HashMap<>()) + .withQueryStringParameters(new HashMap<>()) + .withMultiValueQueryStringParameters(new HashMap<>()) + .withHeaders(new HashMap<>()) + .withMultiValueHeaders(new HashMap<>()) + ); + } catch (Exception e) { + + } + + this.warmUp(); + } @Override - public void warmUp() { - super.warmUp(); - logger.info("LoggingInterceptor: init"); + public void afterRestore(org.crac.Context context) { + } /** - * Return the instance of the logger from the interceptor context + * Override this method to perform any warmup activities which will be executed prior to the snap-start snapshot. */ - public static Logger getLogger(final RequestInput request) { - Object logger = request.getInterceptorContext().get("logger"); - if (logger == null) { - throw new RuntimeException("No logger found. Did you configure the LoggingInterceptor?"); - } - return (Logger) logger; - } + public void warmUp() { - private void addContext(final Context context) { - LoggingUtils.appendKey("functionName", context.getFunctionName()); - LoggingUtils.appendKey("functionVersion", context.getFunctionVersion()); - LoggingUtils.appendKey("functionArn", context.getInvokedFunctionArn()); - LoggingUtils.appendKey("functionMemorySize", String.valueOf(context.getMemoryLimitInMB())); - // Same casing as powertools aspect implementation - LoggingUtils.appendKey("function_request_id", String.valueOf(context.getAwsRequestId())); } @Override - public Response handle(final ChainedRequestInput input) { - // Add lambda context fields - this.addContext(input.getContext()); + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) { + return this.handleRequestWithAdditionalInterceptors(event, context, new ArrayList<>()); + } - // Add service, cold start and tracing - LoggingUtils.appendKey("service", LambdaHandlerProcessor.serviceName()); - LoggingUtils.appendKey("coldStart", LambdaHandlerProcessor.isColdStart() ? "true" : "false"); - LambdaHandlerProcessor.getXrayTraceId().ifPresent((xRayTraceId) -> { - LoggingUtils.appendKey("xray_trace_id", xRayTraceId); - }); + private Map getErrorResponseHeaders(final int statusCode) { + Map headers = new HashMap<>(); + return headers; + } - // Add the operation id - String operationId = (String) input.getInterceptorContext().get("operationId"); - LoggingUtils.appendKey("operationId", operationId); + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { + final Map interceptorContext = new HashMap<>(); + interceptorContext.put("operationId", "inlineRequestBody"); - // Add the logger to the interceptor context - input.getInterceptorContext().put("logger", logger); + List> interceptors = new ArrayList<>(); + interceptors.addAll(additionalInterceptors); + interceptors.addAll(this.getHandlerInterceptors()); - Response response = input.getChain().next(input); + final HandlerChain chain = this.buildChain(interceptors); - // Mark cold start done - LambdaHandlerProcessor.coldStartDone(); + InlineRequestBodyInput input; - // Clear the logger keys - ThreadContext.clearMap(); + try { + input = new InlineRequestBodyInput(event); + } catch (RuntimeException e) { + Map headers = new HashMap<>(); + headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); + headers.putAll(this.getErrorResponseHeaders(400)); + return new APIGatewayProxyResponseEvent() + .withStatusCode(400) + .withHeaders(headers) + .withBody("{\\"message\\": \\"" + e.getMessage() + "\\"}"); + } - return response; + final Response response = chain.next(this.buildChainedRequestInput(event, context, input, interceptorContext)); + + Map responseHeaders = new HashMap<>(); + responseHeaders.putAll(this.getErrorResponseHeaders(response.getStatusCode())); + responseHeaders.putAll(response.getHeaders()); + + return new APIGatewayProxyResponseEvent() + .withStatusCode(response.getStatusCode()) + .withHeaders(responseHeaders) + .withMultiValueHeaders(response.getMultiValueHeaders()) + .withBody(response.getBody()); } } ", - "src/main/java/test/test/runtime/api/interceptors/powertools/MetricsInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody204Response.java": " +package test.test.runtime.api.handlers.inline_request_body; -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.RequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger; -import software.amazon.cloudwatchlogs.emf.model.DimensionSet; -import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; -import software.amazon.lambda.powertools.metrics.MetricsUtils; +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.Map; +import java.util.HashMap; +import java.util.List; /** - * Interceptor which adds an instance of aws lambda powertools metrics to the interceptor context (under the key "metrics"), - * and ensures metrics are flushed prior to finishing the lambda execution - * See: https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics + * Response with status code 204 for the inlineRequestBody operation */ -public class MetricsInterceptor extends InterceptorWithWarmup { - private MetricsLogger metrics = MetricsUtils.metricsLogger(); - - /** - * Return the instance of the metrics logger from the interceptor context - */ - public static MetricsLogger getMetrics(final RequestInput request) { - Object metrics = request.getInterceptorContext().get("metrics"); - if (metrics == null) { - throw new RuntimeException("No metrics logger found. Did you configure the MetricsInterceptor?"); +public class InlineRequestBody204Response extends RuntimeException implements InlineRequestBodyResponse { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); } - return (MetricsLogger) metrics; + } + + private final String body; + + private final Map headers; + private final Map> multiValueHeaders; + + private InlineRequestBody204Response(final Map headers, final Map> multiValueHeaders) { + + this.body = ""; + this.headers = headers; + this.multiValueHeaders = multiValueHeaders; } @Override - public Response handle(final ChainedRequestInput input) { - metrics.putDimensions(DimensionSet.of("operationId", (String) input.getInterceptorContext().get("operationId"))); + public int getStatusCode() { + return 204; + } - input.getInterceptorContext().put("metrics", metrics); + @Override + public String getBody() { + return this.body; + } - metrics.putProperty("function_request_id", input.getContext().getAwsRequestId()); - LambdaHandlerProcessor.getXrayTraceId().ifPresent((traceId) -> { - metrics.putProperty("xray_trace_id", traceId); - }); - try { - Response response = input.getChain().next(input); + @Override + public Map getHeaders() { + return this.headers; + } - // Mark cold start done - LambdaHandlerProcessor.coldStartDone(); + @Override + public Map> getMultiValueHeaders() { + return this.multiValueHeaders; + } - return response; - } finally { - metrics.flush(); - } + /** + * Create a InlineRequestBody204Response without a body + */ + public static InlineRequestBody204Response of() { + return new InlineRequestBody204Response(new HashMap<>(), new HashMap<>()); } -} -", - "src/main/java/test/test/runtime/api/interceptors/powertools/TracingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import com.amazonaws.xray.AWSXRay; -import com.amazonaws.xray.AWSXRayRecorderBuilder; -import com.amazonaws.xray.entities.Subsegment; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.apache.logging.log4j.Logger; -import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; -import software.amazon.lambda.powertools.tracing.TracingUtils; + /** + * Create a InlineRequestBody204Response without a body and headers + */ + public static InlineRequestBody204Response of(final Map headers) { + return new InlineRequestBody204Response(headers, new HashMap<>()); + } + + /** + * Create a InlineRequestBody204Response without a body, headers and multi-value headers + */ + public static InlineRequestBody204Response of(final Map headers, final Map> multiValueHeaders) { + return new InlineRequestBody204Response(headers, multiValueHeaders); + } +} +", + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java": " +package test.test.runtime.api.handlers.inline_request_body; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; /** - * Interceptor which adds an aws lambda powertools tracer to the interceptor context, - * creating the appropriate segment for the handler execution and annotating with recommended - * details. - * See: https://docs.powertools.aws.dev/lambda/java/latest/core/tracing/ + * Input for the inlineRequestBody operation */ -public class TracingInterceptor extends InterceptorWithWarmup { - +@lombok.Builder +@lombok.AllArgsConstructor +public class InlineRequestBodyInput { static { - AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); - AWSXRay.setGlobalRecorder(builder.build()); + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } } - private final boolean captureResponse; - - public TracingInterceptor(final boolean captureResponse) { - this.captureResponse = captureResponse; - } + private final InlineRequestBodyRequestParameters requestParameters; + private final InlineRequestBodyRequestContent body; - public TracingInterceptor() { - this(false); + public InlineRequestBodyInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new InlineRequestBodyRequestParameters(event); + try { + this.body = InlineRequestBodyRequestContent.fromJson(event.getBody()); + } catch (IOException e) { + throw new RuntimeException(e); + }; } - @Override - public void warmUp() { - try { - // Set a dummy trace header to ensure the regular subsegment code path is followed and warmed. - // The segment is not actually recorded by xray. - System.setProperty("com.amazonaws.xray.traceHeader", "Root=1-xxx;Parent=yyy;Sampled=1"); - super.warmUp(); - } finally { - System.clearProperty("com.amazonaws.xray.traceHeader"); - } + public InlineRequestBodyRequestParameters getRequestParameters() { + return this.requestParameters; } - private void logError(final String message, final ChainedRequestInput input, final Throwable e) { - Object logger = input.getInterceptorContext().get("logger"); - if (logger instanceof Logger) { - ((Logger) logger).error(message, e); - } else { - System.err.println(message); - e.printStackTrace(); - } + public InlineRequestBodyRequestContent getBody() { + return this.body; } +} +", + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java": " +package test.test.runtime.api.handlers.inline_request_body; - @Override - public Response handle(final ChainedRequestInput input) { - String operationId = (String) input.getInterceptorContext().get("operationId"); - Subsegment segment = AWSXRay.beginSubsegment("## " + operationId); +import test.test.runtime.model.*; +import test.test.runtime.api.handlers.RequestInput; +import java.util.List; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; - segment.setNamespace(operationId); - segment.putAnnotation("ColdStart", LambdaHandlerProcessor.isColdStart()); - segment.putAnnotation("Service", LambdaHandlerProcessor.serviceName()); +/** + * Full request input for the inlineRequestBody operation, including the raw API Gateway event + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class InlineRequestBodyRequestInput implements RequestInput { + private final APIGatewayProxyRequestEvent event; + private final Context context; + private final Map interceptorContext; + private final InlineRequestBodyInput input; - try { - Response response = input.getChain().next(input); + /** + * Returns the typed request input, with path, query and body parameters + */ + public InlineRequestBodyInput getInput() { + return this.input; + } - try { - if (this.captureResponse) { - segment.putMetadata(operationId + " response", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(response) : response); - } - } catch (JsonProcessingException e) { - this.logError("Failed to add response to trace", input, e); - } + /** + * Returns the raw API Gateway event + */ + public APIGatewayProxyRequestEvent getEvent() { + return this.event; + } - // Mark cold start done - LambdaHandlerProcessor.coldStartDone(); + /** + * Returns the lambda context + */ + public Context getContext() { + return this.context; + } - return response; - } catch (Throwable e) { - try { - segment.putMetadata(operationId + " error", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(e) : e); - } catch (JsonProcessingException ex) { - this.logError("Failed to add error to trace", input, e); - } - throw e; - } finally { - if (!LambdaHandlerProcessor.isSamLocal()) { - AWSXRay.endSubsegment(); - } - } + /** + * Returns the interceptor context, which may contain values set by request interceptors + */ + public Map getInterceptorContext() { + return this.interceptorContext; } } ", - "src/main/java/test/test/runtime/api/operation_config/OperationConfig.java": "package test.test.runtime.api.operation_config; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestParameters.java": " +package test.test.runtime.api.handlers.inline_request_body; + +import test.test.runtime.api.handlers.Handlers; +import java.util.Optional; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.time.OffsetDateTime; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.stream.Collectors; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import test.test.runtime.model.*; -import java.util.HashMap; -import java.util.Map; +/** + * Query, path and header parameters for the InlineRequestBody operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class InlineRequestBodyRequestParameters { -// Generic type for object "keyed" by operation names -@lombok.Builder @lombok.Getter -public class OperationConfig { - private T arrayRequestParameters; - private T inlineEnum; - private T inlineRequestBody; - private T reservedKeywords; + public InlineRequestBodyRequestParameters(final APIGatewayProxyRequestEvent event) { + Map rawStringParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getHeaders(), rawStringParameters); + Map decodedStringParameters = Handlers.decodeRequestParameters(rawStringParameters); + + Map> rawStringArrayParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getMultiValueQueryStringParameters(), rawStringArrayParameters); + Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); + Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); - public Map asMap() { - Map map = new HashMap<>(); - map.put("arrayRequestParameters", this.arrayRequestParameters); - map.put("inlineEnum", this.inlineEnum); - map.put("inlineRequestBody", this.inlineRequestBody); - map.put("reservedKeywords", this.reservedKeywords); - return map; } + } ", - "src/main/java/test/test/runtime/api/operation_config/OperationLookup.java": "package test.test.runtime.api.operation_config; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java": " +package test.test.runtime.api.handlers.inline_request_body; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the inlineRequestBody operation + */ +public interface InlineRequestBodyResponse extends Response {} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf.java": " +package test.test.runtime.api.handlers.named_one_of; import test.test.runtime.model.*; +import test.test.runtime.JSON; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; -import java.util.HashMap; -import java.util.Map; import java.util.List; -import java.util.Arrays; - +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import java.util.Collections; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import org.crac.Core; +import org.crac.Resource; -// Look up path and http method for a given operation name -public class OperationLookup { - @lombok.Builder @lombok.Getter - public static class OperationLookupEntry { - private String method; - private String path; - private List contentTypes; - } - /** - * Returns the operation lookup information for the TypeSafeRestApi construct +/** + * Lambda handler wrapper for the namedOneOf operation + */ +public abstract class NamedOneOf implements RequestHandler, Resource { + { + Core.getGlobalContext().register(this); + } + + /** + * Handle the request for the namedOneOf operation */ - public static Map getOperationLookup() { - final Map config = new HashMap<>(); + public abstract NamedOneOfResponse handle(final NamedOneOfRequestInput request); - config.put("arrayRequestParameters", OperationLookupEntry.builder() - .path("/array-request-parameters") - .method("GET") - .contentTypes(Arrays.asList("application/json")) - .build()); - config.put("inlineEnum", OperationLookupEntry.builder() - .path("/inline-enum") - .method("GET") - .contentTypes(Arrays.asList("application/json")) - .build()); - config.put("inlineRequestBody", OperationLookupEntry.builder() - .path("/inline-request-body") - .method("POST") - .contentTypes(Arrays.asList("application/json")) - .build()); - config.put("reservedKeywords", OperationLookupEntry.builder() - .path("/reserved-keywords") - .method("GET") - .contentTypes(Arrays.asList("application/json")) - .build()); + /** + * Interceptors that the handler class has been decorated with + */ + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(NamedOneOf.class); + + /** + * For more complex interceptors that require instantiation with parameters, you may override this method to + * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, + * prefer the @Interceptors annotation. + */ + public List> getInterceptors() { + return Collections.emptyList(); + } + + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); + interceptors.addAll(annotationInterceptors); + interceptors.addAll(this.getInterceptors()); + return interceptors; + } + + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return handle(new NamedOneOfRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + } + }); + } + + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final NamedOneOfInput input, final Map interceptorContext) { + return new ChainedRequestInput() { + @Override + public HandlerChain getChain() { + // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining + // chain. + return null; + } + + @Override + public APIGatewayProxyRequestEvent getEvent() { + return event; + } + + @Override + public Context getContext() { + return context; + } + + @Override + public NamedOneOfInput getInput() { + return input; + } + + @Override + public Map getInterceptorContext() { + return interceptorContext; + } + }; + } + + @Override + public void beforeCheckpoint(org.crac.Context context) { + // Prime building the handler chain which can take a few 100ms to JIT. + this.buildChain(this.getHandlerInterceptors()); + this.buildChainedRequestInput(null, null, null, null); + + // Initialise instance of Gson and prime serialisation and deserialisation + new JSON(); + JSON.getGson().fromJson(JSON.getGson().toJson(new ApiResponse("", 0, new HashMap<>(), new HashMap<>())), ApiResponse.class); + + try { + // Prime input validation - this will likely fail for the fake event but ensures the code path is optimised + // ready for a real invocation + new NamedOneOfInput(new APIGatewayProxyRequestEvent() + .withBody("{}") + .withPathParameters(new HashMap<>()) + .withQueryStringParameters(new HashMap<>()) + .withMultiValueQueryStringParameters(new HashMap<>()) + .withHeaders(new HashMap<>()) + .withMultiValueHeaders(new HashMap<>()) + ); + } catch (Exception e) { + + } + + this.warmUp(); + } + + @Override + public void afterRestore(org.crac.Context context) { + + } + + /** + * Override this method to perform any warmup activities which will be executed prior to the snap-start snapshot. + */ + public void warmUp() { + + } + + @Override + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) { + return this.handleRequestWithAdditionalInterceptors(event, context, new ArrayList<>()); + } + + private Map getErrorResponseHeaders(final int statusCode) { + Map headers = new HashMap<>(); + return headers; + } + + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { + final Map interceptorContext = new HashMap<>(); + interceptorContext.put("operationId", "namedOneOf"); + + List> interceptors = new ArrayList<>(); + interceptors.addAll(additionalInterceptors); + interceptors.addAll(this.getHandlerInterceptors()); + + final HandlerChain chain = this.buildChain(interceptors); + + NamedOneOfInput input; + + try { + input = new NamedOneOfInput(event); + } catch (RuntimeException e) { + Map headers = new HashMap<>(); + headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); + headers.putAll(this.getErrorResponseHeaders(400)); + return new APIGatewayProxyResponseEvent() + .withStatusCode(400) + .withHeaders(headers) + .withBody("{\\"message\\": \\"" + e.getMessage() + "\\"}"); + } + + final Response response = chain.next(this.buildChainedRequestInput(event, context, input, interceptorContext)); + + Map responseHeaders = new HashMap<>(); + responseHeaders.putAll(this.getErrorResponseHeaders(response.getStatusCode())); + responseHeaders.putAll(response.getHeaders()); + + return new APIGatewayProxyResponseEvent() + .withStatusCode(response.getStatusCode()) + .withHeaders(responseHeaders) + .withMultiValueHeaders(response.getMultiValueHeaders()) + .withBody(response.getBody()); + } +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf200Response.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.Map; +import java.util.HashMap; +import java.util.List; + +/** + * Response with status code 200 for the namedOneOf operation + */ +public class NamedOneOf200Response extends RuntimeException implements NamedOneOfResponse { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final String body; + private final NamedOneOfUnion typedBody; + private final Map headers; + private final Map> multiValueHeaders; + + private NamedOneOf200Response(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); + this.headers = headers; + this.multiValueHeaders = multiValueHeaders; + } + + @Override + public int getStatusCode() { + return 200; + } + + @Override + public String getBody() { + return this.body; + } + + public NamedOneOfUnion getTypedBody() { + return this.typedBody; + } + + @Override + public Map getHeaders() { + return this.headers; + } + + @Override + public Map> getMultiValueHeaders() { + return this.multiValueHeaders; + } + + /** + * Create a NamedOneOf200Response with a body + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body) { + return new NamedOneOf200Response(body, new HashMap<>(), new HashMap<>()); + } + + /** + * Create a NamedOneOf200Response with a body and headers + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers) { + return new NamedOneOf200Response(body, headers, new HashMap<>()); + } + + /** + * Create a NamedOneOf200Response with a body, headers and multi-value headers + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { + return new NamedOneOf200Response(body, headers, multiValueHeaders); + } +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfInput.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; + +/** + * Input for the namedOneOf operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfInput { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final NamedOneOfRequestParameters requestParameters; + + public NamedOneOfInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new NamedOneOfRequestParameters(event); + } + + public NamedOneOfRequestParameters getRequestParameters() { + return this.requestParameters; + } + +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestInput.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.model.*; +import test.test.runtime.api.handlers.RequestInput; +import java.util.List; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; + +/** + * Full request input for the namedOneOf operation, including the raw API Gateway event + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfRequestInput implements RequestInput { + private final APIGatewayProxyRequestEvent event; + private final Context context; + private final Map interceptorContext; + private final NamedOneOfInput input; + + /** + * Returns the typed request input, with path, query and body parameters + */ + public NamedOneOfInput getInput() { + return this.input; + } + + /** + * Returns the raw API Gateway event + */ + public APIGatewayProxyRequestEvent getEvent() { + return this.event; + } + + /** + * Returns the lambda context + */ + public Context getContext() { + return this.context; + } + + /** + * Returns the interceptor context, which may contain values set by request interceptors + */ + public Map getInterceptorContext() { + return this.interceptorContext; + } +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestParameters.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.api.handlers.Handlers; +import java.util.Optional; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.time.OffsetDateTime; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.stream.Collectors; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; + +import test.test.runtime.model.*; + +/** + * Query, path and header parameters for the NamedOneOf operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfRequestParameters { + + public NamedOneOfRequestParameters(final APIGatewayProxyRequestEvent event) { + Map rawStringParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getHeaders(), rawStringParameters); + Map decodedStringParameters = Handlers.decodeRequestParameters(rawStringParameters); + + Map> rawStringArrayParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getMultiValueQueryStringParameters(), rawStringArrayParameters); + Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); + Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); + + } + +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfResponse.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the namedOneOf operation + */ +public interface NamedOneOfResponse extends Response {} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; + +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import java.util.Collections; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import org.crac.Core; +import org.crac.Resource; + + +/** + * Lambda handler wrapper for the reservedKeywords operation + */ +public abstract class ReservedKeywords implements RequestHandler, Resource { + { + Core.getGlobalContext().register(this); + } + + /** + * Handle the request for the reservedKeywords operation + */ + public abstract ReservedKeywordsResponse handle(final ReservedKeywordsRequestInput request); + + /** + * Interceptors that the handler class has been decorated with + */ + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ReservedKeywords.class); + + /** + * For more complex interceptors that require instantiation with parameters, you may override this method to + * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, + * prefer the @Interceptors annotation. + */ + public List> getInterceptors() { + return Collections.emptyList(); + } + + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); + interceptors.addAll(annotationInterceptors); + interceptors.addAll(this.getInterceptors()); + return interceptors; + } + + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return handle(new ReservedKeywordsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + } + }); + } + + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ReservedKeywordsInput input, final Map interceptorContext) { + return new ChainedRequestInput() { + @Override + public HandlerChain getChain() { + // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining + // chain. + return null; + } + + @Override + public APIGatewayProxyRequestEvent getEvent() { + return event; + } + + @Override + public Context getContext() { + return context; + } + + @Override + public ReservedKeywordsInput getInput() { + return input; + } + + @Override + public Map getInterceptorContext() { + return interceptorContext; + } + }; + } + + @Override + public void beforeCheckpoint(org.crac.Context context) { + // Prime building the handler chain which can take a few 100ms to JIT. + this.buildChain(this.getHandlerInterceptors()); + this.buildChainedRequestInput(null, null, null, null); + + // Initialise instance of Gson and prime serialisation and deserialisation + new JSON(); + JSON.getGson().fromJson(JSON.getGson().toJson(new ApiResponse("", 0, new HashMap<>(), new HashMap<>())), ApiResponse.class); + + try { + // Prime input validation - this will likely fail for the fake event but ensures the code path is optimised + // ready for a real invocation + new ReservedKeywordsInput(new APIGatewayProxyRequestEvent() + .withBody("{}") + .withPathParameters(new HashMap<>()) + .withQueryStringParameters(new HashMap<>()) + .withMultiValueQueryStringParameters(new HashMap<>()) + .withHeaders(new HashMap<>()) + .withMultiValueHeaders(new HashMap<>()) + ); + } catch (Exception e) { + + } + + this.warmUp(); + } + + @Override + public void afterRestore(org.crac.Context context) { + + } + + /** + * Override this method to perform any warmup activities which will be executed prior to the snap-start snapshot. + */ + public void warmUp() { + + } + + @Override + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) { + return this.handleRequestWithAdditionalInterceptors(event, context, new ArrayList<>()); + } + + private Map getErrorResponseHeaders(final int statusCode) { + Map headers = new HashMap<>(); + return headers; + } + + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { + final Map interceptorContext = new HashMap<>(); + interceptorContext.put("operationId", "reservedKeywords"); + + List> interceptors = new ArrayList<>(); + interceptors.addAll(additionalInterceptors); + interceptors.addAll(this.getHandlerInterceptors()); + + final HandlerChain chain = this.buildChain(interceptors); + + ReservedKeywordsInput input; + + try { + input = new ReservedKeywordsInput(event); + } catch (RuntimeException e) { + Map headers = new HashMap<>(); + headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); + headers.putAll(this.getErrorResponseHeaders(400)); + return new APIGatewayProxyResponseEvent() + .withStatusCode(400) + .withHeaders(headers) + .withBody("{\\"message\\": \\"" + e.getMessage() + "\\"}"); + } + + final Response response = chain.next(this.buildChainedRequestInput(event, context, input, interceptorContext)); + + Map responseHeaders = new HashMap<>(); + responseHeaders.putAll(this.getErrorResponseHeaders(response.getStatusCode())); + responseHeaders.putAll(response.getHeaders()); + + return new APIGatewayProxyResponseEvent() + .withStatusCode(response.getStatusCode()) + .withHeaders(responseHeaders) + .withMultiValueHeaders(response.getMultiValueHeaders()) + .withBody(response.getBody()); + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords200Response.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.Map; +import java.util.HashMap; +import java.util.List; + +/** + * Response with status code 200 for the reservedKeywords operation + */ +public class ReservedKeywords200Response extends RuntimeException implements ReservedKeywordsResponse { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final String body; + + private final Map headers; + private final Map> multiValueHeaders; + + private ReservedKeywords200Response(final Map headers, final Map> multiValueHeaders) { + + this.body = ""; + this.headers = headers; + this.multiValueHeaders = multiValueHeaders; + } + + @Override + public int getStatusCode() { + return 200; + } + + @Override + public String getBody() { + return this.body; + } + + + @Override + public Map getHeaders() { + return this.headers; + } + + @Override + public Map> getMultiValueHeaders() { + return this.multiValueHeaders; + } + + /** + * Create a ReservedKeywords200Response without a body + */ + public static ReservedKeywords200Response of() { + return new ReservedKeywords200Response(new HashMap<>(), new HashMap<>()); + } + + /** + * Create a ReservedKeywords200Response without a body and headers + */ + public static ReservedKeywords200Response of(final Map headers) { + return new ReservedKeywords200Response(headers, new HashMap<>()); + } + + /** + * Create a ReservedKeywords200Response without a body, headers and multi-value headers + */ + public static ReservedKeywords200Response of(final Map headers, final Map> multiValueHeaders) { + return new ReservedKeywords200Response(headers, multiValueHeaders); + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsInput.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; + +/** + * Input for the reservedKeywords operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class ReservedKeywordsInput { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final ReservedKeywordsRequestParameters requestParameters; + + public ReservedKeywordsInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new ReservedKeywordsRequestParameters(event); + } + + public ReservedKeywordsRequestParameters getRequestParameters() { + return this.requestParameters; + } + +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestInput.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.api.handlers.RequestInput; +import java.util.List; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; + +/** + * Full request input for the reservedKeywords operation, including the raw API Gateway event + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class ReservedKeywordsRequestInput implements RequestInput { + private final APIGatewayProxyRequestEvent event; + private final Context context; + private final Map interceptorContext; + private final ReservedKeywordsInput input; + + /** + * Returns the typed request input, with path, query and body parameters + */ + public ReservedKeywordsInput getInput() { + return this.input; + } + + /** + * Returns the raw API Gateway event + */ + public APIGatewayProxyRequestEvent getEvent() { + return this.event; + } + + /** + * Returns the lambda context + */ + public Context getContext() { + return this.context; + } + + /** + * Returns the interceptor context, which may contain values set by request interceptors + */ + public Map getInterceptorContext() { + return this.interceptorContext; + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestParameters.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.api.handlers.Handlers; +import java.util.Optional; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.time.OffsetDateTime; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.stream.Collectors; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; + +import test.test.runtime.model.*; + +/** + * Query, path and header parameters for the ReservedKeywords operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class ReservedKeywordsRequestParameters { + private final Optional with; + private final Optional _if; + private final Optional propertyClass; + + public ReservedKeywordsRequestParameters(final APIGatewayProxyRequestEvent event) { + Map rawStringParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getHeaders(), rawStringParameters); + Map decodedStringParameters = Handlers.decodeRequestParameters(rawStringParameters); + + Map> rawStringArrayParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getMultiValueQueryStringParameters(), rawStringArrayParameters); + Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); + Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); + + this.with = Optional.ofNullable(Handlers.coerceStringParameter("with", false, decodedStringParameters)); + this._if = Optional.ofNullable(Handlers.coerceStringParameter("if", false, decodedStringParameters)); + this.propertyClass = Optional.ofNullable(Handlers.coerceStringParameter("class", false, decodedStringParameters)); + } + + public Optional getWith() { + return this.with; + } + public Optional getIf() { + return this._if; + } + public Optional getPropertyClass() { + return this.propertyClass; + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsResponse.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the reservedKeywords operation + */ +public interface ReservedKeywordsResponse extends Response {} +", + "src/main/java/test/test/runtime/api/interceptors/DefaultInterceptors.java": "package test.test.runtime.api.interceptors; + +import test.test.runtime.api.interceptors.powertools.LoggingInterceptor; +import test.test.runtime.api.interceptors.powertools.MetricsInterceptor; +import test.test.runtime.api.interceptors.powertools.TracingInterceptor; +import test.test.runtime.api.handlers.Interceptor; + +import java.util.Arrays; +import java.util.List; + +public class DefaultInterceptors { + public static List> all() { + return Arrays.asList( + new ResponseHeadersInterceptor<>(), + new LoggingInterceptor<>(), + new TryCatchInterceptor<>(), + new TracingInterceptor<>(), + new MetricsInterceptor<>() + ); + } +}", + "src/main/java/test/test/runtime/api/interceptors/ResponseHeadersInterceptor.java": "package test.test.runtime.api.interceptors; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import java.util.Map; +import java.util.HashMap; + +/** + * An interceptor for adding cross-origin resource sharing (CORS) headers to the response. + * Allows all origins and headers. + */ +public class ResponseHeadersInterceptor extends InterceptorWithWarmup { + private final Map additionalHeaders; + + public ResponseHeadersInterceptor() { + this.additionalHeaders = new HashMap<>(); + this.additionalHeaders.put("Access-Control-Allow-Origin", "*"); + this.additionalHeaders.put("Access-Control-Allow-Headers", "*"); + } + + public ResponseHeadersInterceptor(final Map headers) { + this.additionalHeaders = headers; + } + + @Override + public Response handle(ChainedRequestInput input) { + Response res = input.getChain().next(input); + res.getHeaders().putAll(this.additionalHeaders); + return res; + } + + public Map getAdditionalHeaders() { + return this.additionalHeaders; + } +} +", + "src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java": "package test.test.runtime.api.interceptors; + +import test.test.runtime.api.handlers.ApiResponse; +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import org.apache.logging.log4j.Logger; + +/** + * Interceptor for handling uncaught exceptions and responding with a default error response + */ +public class TryCatchInterceptor extends InterceptorWithWarmup { + private final int statusCode; + private final String errorResponseBody; + + public TryCatchInterceptor() { + this(500, "{\\"message\\": \\"Internal Error\\"}"); + } + + public TryCatchInterceptor(final int statusCode, final String errorResponseBody) { + this.statusCode = statusCode; + this.errorResponseBody = errorResponseBody; + } + + @Override + public Response handle(final ChainedRequestInput input) { + try { + return input.getChain().next(input); + } catch (Throwable e) { + if (e instanceof Response) { + return (Response) e; + } + + Object logger = input.getInterceptorContext().get("logger"); + if (logger instanceof Logger) { + ((Logger) logger).error("Interceptor caught exception", e); + } else { + System.err.println("Interceptor caught exception"); + e.printStackTrace(); + } + + return ApiResponse.builder() + .statusCode(this.statusCode) + .body(this.errorResponseBody) + .build(); + } + } +} +", + "src/main/java/test/test/runtime/api/interceptors/powertools/LoggingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.RequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import com.amazonaws.services.lambda.runtime.Context; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.ThreadContext; +import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; +import software.amazon.lambda.powertools.logging.LoggingUtils; + +/** + * An interceptor which adds an aws lambda powertools logger to the interceptor context, + * and adds the lambda context. + * See https://docs.powertools.aws.dev/lambda/java/latest/core/logging/ + */ +public class LoggingInterceptor extends InterceptorWithWarmup { + private Logger logger = LogManager.getLogger(LoggingInterceptor.class); + + @Override + public void warmUp() { + super.warmUp(); + logger.info("LoggingInterceptor: init"); + } + + /** + * Return the instance of the logger from the interceptor context + */ + public static Logger getLogger(final RequestInput request) { + Object logger = request.getInterceptorContext().get("logger"); + if (logger == null) { + throw new RuntimeException("No logger found. Did you configure the LoggingInterceptor?"); + } + return (Logger) logger; + } + + private void addContext(final Context context) { + LoggingUtils.appendKey("functionName", context.getFunctionName()); + LoggingUtils.appendKey("functionVersion", context.getFunctionVersion()); + LoggingUtils.appendKey("functionArn", context.getInvokedFunctionArn()); + LoggingUtils.appendKey("functionMemorySize", String.valueOf(context.getMemoryLimitInMB())); + // Same casing as powertools aspect implementation + LoggingUtils.appendKey("function_request_id", String.valueOf(context.getAwsRequestId())); + } + + @Override + public Response handle(final ChainedRequestInput input) { + // Add lambda context fields + this.addContext(input.getContext()); + + // Add service, cold start and tracing + LoggingUtils.appendKey("service", LambdaHandlerProcessor.serviceName()); + LoggingUtils.appendKey("coldStart", LambdaHandlerProcessor.isColdStart() ? "true" : "false"); + LambdaHandlerProcessor.getXrayTraceId().ifPresent((xRayTraceId) -> { + LoggingUtils.appendKey("xray_trace_id", xRayTraceId); + }); + + // Add the operation id + String operationId = (String) input.getInterceptorContext().get("operationId"); + LoggingUtils.appendKey("operationId", operationId); + + // Add the logger to the interceptor context + input.getInterceptorContext().put("logger", logger); + + Response response = input.getChain().next(input); + + // Mark cold start done + LambdaHandlerProcessor.coldStartDone(); + + // Clear the logger keys + ThreadContext.clearMap(); + + return response; + } +} +", + "src/main/java/test/test/runtime/api/interceptors/powertools/MetricsInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.RequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger; +import software.amazon.cloudwatchlogs.emf.model.DimensionSet; +import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; +import software.amazon.lambda.powertools.metrics.MetricsUtils; + +/** + * Interceptor which adds an instance of aws lambda powertools metrics to the interceptor context (under the key "metrics"), + * and ensures metrics are flushed prior to finishing the lambda execution + * See: https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics + */ +public class MetricsInterceptor extends InterceptorWithWarmup { + private MetricsLogger metrics = MetricsUtils.metricsLogger(); + + /** + * Return the instance of the metrics logger from the interceptor context + */ + public static MetricsLogger getMetrics(final RequestInput request) { + Object metrics = request.getInterceptorContext().get("metrics"); + if (metrics == null) { + throw new RuntimeException("No metrics logger found. Did you configure the MetricsInterceptor?"); + } + return (MetricsLogger) metrics; + } + + @Override + public Response handle(final ChainedRequestInput input) { + metrics.putDimensions(DimensionSet.of("operationId", (String) input.getInterceptorContext().get("operationId"))); + + input.getInterceptorContext().put("metrics", metrics); + + metrics.putProperty("function_request_id", input.getContext().getAwsRequestId()); + LambdaHandlerProcessor.getXrayTraceId().ifPresent((traceId) -> { + metrics.putProperty("xray_trace_id", traceId); + }); + + try { + Response response = input.getChain().next(input); + + // Mark cold start done + LambdaHandlerProcessor.coldStartDone(); + + return response; + } finally { + metrics.flush(); + } + } +} +", + "src/main/java/test/test/runtime/api/interceptors/powertools/TracingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import com.amazonaws.xray.AWSXRay; +import com.amazonaws.xray.AWSXRayRecorderBuilder; +import com.amazonaws.xray.entities.Subsegment; +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.logging.log4j.Logger; +import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; +import software.amazon.lambda.powertools.tracing.TracingUtils; + +/** + * Interceptor which adds an aws lambda powertools tracer to the interceptor context, + * creating the appropriate segment for the handler execution and annotating with recommended + * details. + * See: https://docs.powertools.aws.dev/lambda/java/latest/core/tracing/ + */ +public class TracingInterceptor extends InterceptorWithWarmup { + + static { + AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); + AWSXRay.setGlobalRecorder(builder.build()); + } + + private final boolean captureResponse; + + public TracingInterceptor(final boolean captureResponse) { + this.captureResponse = captureResponse; + } + + public TracingInterceptor() { + this(false); + } + + @Override + public void warmUp() { + try { + // Set a dummy trace header to ensure the regular subsegment code path is followed and warmed. + // The segment is not actually recorded by xray. + System.setProperty("com.amazonaws.xray.traceHeader", "Root=1-xxx;Parent=yyy;Sampled=1"); + super.warmUp(); + } finally { + System.clearProperty("com.amazonaws.xray.traceHeader"); + } + } + + private void logError(final String message, final ChainedRequestInput input, final Throwable e) { + Object logger = input.getInterceptorContext().get("logger"); + if (logger instanceof Logger) { + ((Logger) logger).error(message, e); + } else { + System.err.println(message); + e.printStackTrace(); + } + } + + @Override + public Response handle(final ChainedRequestInput input) { + String operationId = (String) input.getInterceptorContext().get("operationId"); + Subsegment segment = AWSXRay.beginSubsegment("## " + operationId); + + segment.setNamespace(operationId); + segment.putAnnotation("ColdStart", LambdaHandlerProcessor.isColdStart()); + segment.putAnnotation("Service", LambdaHandlerProcessor.serviceName()); + + try { + Response response = input.getChain().next(input); + + try { + if (this.captureResponse) { + segment.putMetadata(operationId + " response", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(response) : response); + } + } catch (JsonProcessingException e) { + this.logError("Failed to add response to trace", input, e); + } + + // Mark cold start done + LambdaHandlerProcessor.coldStartDone(); + + return response; + } catch (Throwable e) { + try { + segment.putMetadata(operationId + " error", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(e) : e); + } catch (JsonProcessingException ex) { + this.logError("Failed to add error to trace", input, e); + } + throw e; + } finally { + if (!LambdaHandlerProcessor.isSamLocal()) { + AWSXRay.endSubsegment(); + } + } + } +} +", + "src/main/java/test/test/runtime/api/operation_config/OperationConfig.java": "package test.test.runtime.api.operation_config; + +import test.test.runtime.model.*; + +import java.util.HashMap; +import java.util.Map; + +// Generic type for object "keyed" by operation names +@lombok.Builder @lombok.Getter +public class OperationConfig { + private T arrayOfOneOfs; + private T arrayRequestParameters; + private T dictionary; + private T inlineEnum; + private T inlineRequestBody; + private T namedOneOf; + private T reservedKeywords; + + public Map asMap() { + Map map = new HashMap<>(); + map.put("arrayOfOneOfs", this.arrayOfOneOfs); + map.put("arrayRequestParameters", this.arrayRequestParameters); + map.put("dictionary", this.dictionary); + map.put("inlineEnum", this.inlineEnum); + map.put("inlineRequestBody", this.inlineRequestBody); + map.put("namedOneOf", this.namedOneOf); + map.put("reservedKeywords", this.reservedKeywords); + return map; + } +} +", + "src/main/java/test/test/runtime/api/operation_config/OperationLookup.java": "package test.test.runtime.api.operation_config; + +import test.test.runtime.model.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.Arrays; + + +// Look up path and http method for a given operation name +public class OperationLookup { + @lombok.Builder @lombok.Getter + public static class OperationLookupEntry { + private String method; + private String path; + private List contentTypes; + } + + /** + * Returns the operation lookup information for the TypeSafeRestApi construct + */ + public static Map getOperationLookup() { + final Map config = new HashMap<>(); + + config.put("arrayOfOneOfs", OperationLookupEntry.builder() + .path("/array-of-one-ofs") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("arrayRequestParameters", OperationLookupEntry.builder() + .path("/array-request-parameters") + .method("GET") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("dictionary", OperationLookupEntry.builder() + .path("/additional-properties") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("inlineEnum", OperationLookupEntry.builder() + .path("/inline-enum") + .method("GET") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("inlineRequestBody", OperationLookupEntry.builder() + .path("/inline-request-body") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("namedOneOf", OperationLookupEntry.builder() + .path("/named-one-of") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("reservedKeywords", OperationLookupEntry.builder() + .path("/reserved-keywords") + .method("GET") + .contentTypes(Arrays.asList("application/json")) + .build()); + + return config; + } +} +", + "src/main/java/test/test/runtime/api/operation_config/Operations.java": "package test.test.runtime.api.operation_config; + +public class Operations { + /** + * Returns an OperationConfig Builder with all values populated with the given value. + * You can override specific values on the builder if you like. + * Make sure you call \`.build()\` at the end to construct the OperationConfig. + */ + public static OperationConfig.OperationConfigBuilder all(final T value) { + return OperationConfig.builder() + .arrayOfOneOfs(value) + .arrayRequestParameters(value) + .dictionary(value) + .inlineEnum(value) + .inlineRequestBody(value) + .namedOneOf(value) + .reservedKeywords(value) + ; + } +} +", + "src/main/java/test/test/runtime/auth/ApiKeyAuth.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.ApiException; +import test.test.runtime.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +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, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + 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); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} +", + "src/main/java/test/test/runtime/auth/Authentication.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.Pair; +import test.test.runtime.ApiException; + +import java.net.URI; +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 + * @param cookieParams Map of cookie parameters + * @param payload HTTP request body + * @param method HTTP method + * @param uri URI + * @throws ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; +} +", + "src/main/java/test/test/runtime/auth/HttpBasicAuth.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.Pair; +import test.test.runtime.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); + } +} +", + "src/main/java/test/test/runtime/auth/HttpBearerAuth.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.ApiException; +import test.test.runtime.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return bearerToken; + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} +", + "src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import test.test.runtime.ApiException; +import java.util.Objects; +import java.lang.reflect.Type; +import java.util.Map; +import javax.ws.rs.core.GenericType; + +//import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + //@JsonValue + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).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 "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} +", + "src/main/java/test/test/runtime/model/AdditionalPropertiesResponse.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import test.test.runtime.model.Dictionary; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * AdditionalPropertiesResponse + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class AdditionalPropertiesResponse { + public static final String SERIALIZED_NAME_DICTIONARY_OF_OBJECTS = "dictionaryOfObjects"; + @SerializedName(SERIALIZED_NAME_DICTIONARY_OF_OBJECTS) + private Dictionary dictionaryOfObjects; + + public static final String SERIALIZED_NAME_DICTIONARY_OF_PRIMITIVES = "dictionaryOfPrimitives"; + @SerializedName(SERIALIZED_NAME_DICTIONARY_OF_PRIMITIVES) + private Map dictionaryOfPrimitives = null; + + public AdditionalPropertiesResponse() { + } + + public AdditionalPropertiesResponse dictionaryOfObjects(Dictionary dictionaryOfObjects) { + + this.dictionaryOfObjects = dictionaryOfObjects; + return this; + } + + /** + * Get dictionaryOfObjects + * @return dictionaryOfObjects + **/ + @javax.annotation.Nullable + public Dictionary getDictionaryOfObjects() { + return dictionaryOfObjects; + } + + + public void setDictionaryOfObjects(Dictionary dictionaryOfObjects) { + this.dictionaryOfObjects = dictionaryOfObjects; + } + + public AdditionalPropertiesResponse dictionaryOfPrimitives(Map dictionaryOfPrimitives) { + + this.dictionaryOfPrimitives = dictionaryOfPrimitives; + return this; + } + + public AdditionalPropertiesResponse putDictionaryOfPrimitivesItem(String key, String dictionaryOfPrimitivesItem) { + if (this.dictionaryOfPrimitives == null) { + this.dictionaryOfPrimitives = new HashMap<>(); + } + this.dictionaryOfPrimitives.put(key, dictionaryOfPrimitivesItem); + return this; + } + + /** + * Get dictionaryOfPrimitives + * @return dictionaryOfPrimitives + **/ + @javax.annotation.Nullable + public Map getDictionaryOfPrimitives() { + return dictionaryOfPrimitives; + } + + + public void setDictionaryOfPrimitives(Map dictionaryOfPrimitives) { + this.dictionaryOfPrimitives = dictionaryOfPrimitives; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesResponse additionalPropertiesResponse = (AdditionalPropertiesResponse) o; + return Objects.equals(this.dictionaryOfObjects, additionalPropertiesResponse.dictionaryOfObjects) && + Objects.equals(this.dictionaryOfPrimitives, additionalPropertiesResponse.dictionaryOfPrimitives); + + } + + @Override + public int hashCode() { + return Objects.hash(dictionaryOfObjects, dictionaryOfPrimitives); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesResponse {\\n"); + sb.append(" dictionaryOfObjects: ").append(toIndentedString(dictionaryOfObjects)).append("\\n"); + sb.append(" dictionaryOfPrimitives: ").append(toIndentedString(dictionaryOfPrimitives)).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 "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("dictionaryOfObjects"); + openapiFields.add("dictionaryOfPrimitives"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesResponse + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!AdditionalPropertiesResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesResponse is not found in the empty JSON string", AdditionalPropertiesResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!AdditionalPropertiesResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AdditionalPropertiesResponse\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // validate the optional field \`dictionaryOfObjects\` + if (jsonObj.get("dictionaryOfObjects") != null && !jsonObj.get("dictionaryOfObjects").isJsonNull()) { + Dictionary.validateJsonObject(jsonObj.getAsJsonObject("dictionaryOfObjects")); + } + if ((jsonObj.get("dictionaryOfPrimitives") != null && !jsonObj.get("dictionaryOfPrimitives").isJsonNull()) && !jsonObj.get("dictionaryOfPrimitives").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`dictionaryOfPrimitives\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("dictionaryOfPrimitives").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AdditionalPropertiesResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AdditionalPropertiesResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AdditionalPropertiesResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AdditionalPropertiesResponse read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AdditionalPropertiesResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of AdditionalPropertiesResponse + * @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesResponse + */ + public static AdditionalPropertiesResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AdditionalPropertiesResponse.class); + } + + /** + * Convert an instance of AdditionalPropertiesResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} +", + "src/main/java/test/test/runtime/model/AnotherNamedOneOf.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * AnotherNamedOneOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class AnotherNamedOneOf { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + private String bar; + + public AnotherNamedOneOf() { + } + + public AnotherNamedOneOf bar(String bar) { + + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @javax.annotation.Nullable + public String getBar() { + return bar; + } + + + public void setBar(String bar) { + this.bar = bar; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnotherNamedOneOf anotherNamedOneOf = (AnotherNamedOneOf) o; + return Objects.equals(this.bar, anotherNamedOneOf.bar); + + } + + @Override + public int hashCode() { + return Objects.hash(bar); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnotherNamedOneOf {\\n"); + sb.append(" bar: ").append(toIndentedString(bar)).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 "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("bar"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to AnotherNamedOneOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!AnotherNamedOneOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AnotherNamedOneOf is not found in the empty JSON string", AnotherNamedOneOf.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!AnotherNamedOneOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AnotherNamedOneOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`bar\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("bar").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AnotherNamedOneOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AnotherNamedOneOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AnotherNamedOneOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AnotherNamedOneOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AnotherNamedOneOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AnotherNamedOneOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of AnotherNamedOneOf + * @throws IOException if the JSON string is invalid with respect to AnotherNamedOneOf + */ + public static AnotherNamedOneOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AnotherNamedOneOf.class); + } + + /** + * Convert an instance of AnotherNamedOneOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} +", + "src/main/java/test/test/runtime/model/ArrayOfOneOfs.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import test.test.runtime.model.NamedOneOfUnion; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * ArrayOfOneOfs + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class ArrayOfOneOfs { + public static final String SERIALIZED_NAME_ONE_OFS = "oneOfs"; + @SerializedName(SERIALIZED_NAME_ONE_OFS) + private List oneOfs = null; + + public ArrayOfOneOfs() { + } + + public ArrayOfOneOfs oneOfs(List oneOfs) { + + this.oneOfs = oneOfs; + return this; + } + + public ArrayOfOneOfs addOneOfsItem(NamedOneOfUnion oneOfsItem) { + if (this.oneOfs == null) { + this.oneOfs = new ArrayList<>(); + } + this.oneOfs.add(oneOfsItem); + return this; + } + + /** + * Get oneOfs + * @return oneOfs + **/ + @javax.annotation.Nullable + public List getOneOfs() { + return oneOfs; + } + + + public void setOneOfs(List oneOfs) { + this.oneOfs = oneOfs; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfOneOfs arrayOfOneOfs = (ArrayOfOneOfs) o; + return Objects.equals(this.oneOfs, arrayOfOneOfs.oneOfs); + + } + + @Override + public int hashCode() { + return Objects.hash(oneOfs); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfOneOfs {\\n"); + sb.append(" oneOfs: ").append(toIndentedString(oneOfs)).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 "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("oneOfs"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to ArrayOfOneOfs + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!ArrayOfOneOfs.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfOneOfs is not found in the empty JSON string", ArrayOfOneOfs.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!ArrayOfOneOfs.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`ArrayOfOneOfs\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // ensure the optional json data is an array if present + if (jsonObj.get("oneOfs") != null && !jsonObj.get("oneOfs").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field \`oneOfs\` to be an array in the JSON string but got \`%s\`", jsonObj.get("oneOfs").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfOneOfs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfOneOfs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfOneOfs.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfOneOfs value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfOneOfs read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayOfOneOfs given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfOneOfs + * @throws IOException if the JSON string is invalid with respect to ArrayOfOneOfs + */ + public static ArrayOfOneOfs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfOneOfs.class); + } + + /** + * Convert an instance of ArrayOfOneOfs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} +", + "src/main/java/test/test/runtime/model/Dictionary.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * Dictionary + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class Dictionary { + public Dictionary() { + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dictionary dictionary = (Dictionary) o; + return + } + + @Override + public int hashCode() { + return Objects.hash(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dictionary {\\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 "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to Dictionary + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!Dictionary.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in Dictionary is not found in the empty JSON string", Dictionary.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!Dictionary.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`Dictionary\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + } - return config; - } -} -", - "src/main/java/test/test/runtime/api/operation_config/Operations.java": "package test.test.runtime.api.operation_config; + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Dictionary.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Dictionary' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Dictionary.class)); -public class Operations { - /** - * Returns an OperationConfig Builder with all values populated with the given value. - * You can override specific values on the builder if you like. - * Make sure you call \`.build()\` at the end to construct the OperationConfig. - */ - public static OperationConfig.OperationConfigBuilder all(final T value) { - return OperationConfig.builder() - .arrayRequestParameters(value) - .inlineEnum(value) - .inlineRequestBody(value) - .reservedKeywords(value) - ; + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Dictionary value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Dictionary read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); } + } + + /** + * Create an instance of Dictionary given an JSON string + * + * @param jsonString JSON string + * @return An instance of Dictionary + * @throws IOException if the JSON string is invalid with respect to Dictionary + */ + public static Dictionary fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Dictionary.class); + } + + /** + * Convert an instance of Dictionary to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } } ", - "src/main/java/test/test/runtime/auth/ApiKeyAuth.java": "/* + "src/main/java/test/test/runtime/model/InlineEnum200Response.java": "/* * Edge Cases * * @@ -36914,74 +39974,222 @@ public class Operations { */ -package test.test.runtime.auth; +package test.test.runtime.model; -import test.test.runtime.ApiException; -import test.test.runtime.Pair; +import java.util.Objects; +import java.util.Arrays; +import test.test.runtime.model.InlineEnum200ResponseCategoryEnum; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.List; +import java.util.Set; -public class ApiKeyAuth implements Authentication { - private final String location; - private final String paramName; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; - private String apiKey; - private String apiKeyPrefix; +import test.test.runtime.JSON; - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; +/** + * InlineEnum200Response + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class InlineEnum200Response { + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + private InlineEnum200ResponseCategoryEnum category; + + public InlineEnum200Response() { } - public String getLocation() { - return location; + public InlineEnum200Response category(InlineEnum200ResponseCategoryEnum category) { + + this.category = category; + return this; } - public String getParamName() { - return paramName; + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + public InlineEnum200ResponseCategoryEnum getCategory() { + return category; } - public String getApiKey() { - return apiKey; + + public void setCategory(InlineEnum200ResponseCategoryEnum category) { + this.category = category; } - public void setApiKey(String apiKey) { - this.apiKey = apiKey; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + InlineEnum200Response inlineEnum200Response = (InlineEnum200Response) o; + return Objects.equals(this.category, inlineEnum200Response.category); + } - public String getApiKeyPrefix() { - return apiKeyPrefix; + @Override + public int hashCode() { + return Objects.hash(category); } - public void setApiKeyPrefix(String apiKeyPrefix) { - this.apiKeyPrefix = apiKeyPrefix; + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineEnum200Response {\\n"); + sb.append(" category: ").append(toIndentedString(category)).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 "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("category"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to InlineEnum200Response + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!InlineEnum200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in InlineEnum200Response is not found in the empty JSON string", InlineEnum200Response.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!InlineEnum200Response.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineEnum200Response\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // validate the optional field \`category\` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + InlineEnum200ResponseCategoryEnum.validateJsonObject(jsonObj.getAsJsonObject("category")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!InlineEnum200Response.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'InlineEnum200Response' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(InlineEnum200Response.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, InlineEnum200Response value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public InlineEnum200Response read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of InlineEnum200Response given an JSON string + * + * @param jsonString JSON string + * @return An instance of InlineEnum200Response + * @throws IOException if the JSON string is invalid with respect to InlineEnum200Response + */ + public static InlineEnum200Response fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, InlineEnum200Response.class); } - @Override - public void applyToParams(List queryParams, Map headerParams, Map cookieParams, - String payload, String method, URI uri) throws ApiException { - 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); - } else if ("cookie".equals(location)) { - cookieParams.put(paramName, value); - } + /** + * Convert an instance of InlineEnum200Response to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); } } ", - "src/main/java/test/test/runtime/auth/Authentication.java": "/* + "src/main/java/test/test/runtime/model/InlineEnum200ResponseCategoryEnum.java": "/* * Edge Cases * * @@ -36993,88 +40201,109 @@ public class ApiKeyAuth implements Authentication { */ -package test.test.runtime.auth; +package test.test.runtime.model; -import test.test.runtime.Pair; -import test.test.runtime.ApiException; +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.List; +import java.util.Set; -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws ApiException if failed to update the parameters - */ - void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; -} -", - "src/main/java/test/test/runtime/auth/HttpBasicAuth.java": "/* - * Edge Cases - * - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated. - * Do not edit the class manually. - */ - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; -package test.test.runtime.auth; +import test.test.runtime.JSON; -import test.test.runtime.Pair; -import test.test.runtime.ApiException; +/** + * Gets or Sets InlineEnum200ResponseCategoryEnum + */ +@JsonAdapter(InlineEnum200ResponseCategoryEnum.Adapter.class) +public enum InlineEnum200ResponseCategoryEnum { -import okhttp3.Credentials; + FRUIT("fruit"), -import java.net.URI; -import java.util.Map; -import java.util.List; + VEGETABLE("vegetable"); -import java.io.UnsupportedEncodingException; + private String value; -public class HttpBasicAuth implements Authentication { - private String username; - private String password; + InlineEnum200ResponseCategoryEnum(String value) { + this.value = value; + } - public String getUsername() { - return username; - } + public String getValue() { + return value; + } - public void setUsername(String username) { - this.username = username; - } + @Override + public String toString() { + return String.valueOf(value); + } - public String getPassword() { - return password; + public static InlineEnum200ResponseCategoryEnum fromValue(String value) { + for (InlineEnum200ResponseCategoryEnum b : InlineEnum200ResponseCategoryEnum.values()) { + if (b.value.equals(value)) { + return b; + } } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } - public void setPassword(String password) { - this.password = password; + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final InlineEnum200ResponseCategoryEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); } @Override - public void applyToParams(List queryParams, Map headerParams, Map cookieParams, - String payload, String method, URI uri) throws ApiException { - if (username == null && password == null) { - return; - } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); + public InlineEnum200ResponseCategoryEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return InlineEnum200ResponseCategoryEnum.fromValue(value); } + } } ", - "src/main/java/test/test/runtime/auth/HttpBearerAuth.java": "/* + "src/main/java/test/test/runtime/model/InlineRequestBodyRequestContent.java": "/* * Edge Cases * * @@ -37086,57 +40315,228 @@ public class HttpBasicAuth implements Authentication { */ -package test.test.runtime.auth; +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * InlineRequestBodyRequestContent + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class InlineRequestBodyRequestContent { + public static final String SERIALIZED_NAME_SOME_PROPERTY = "someProperty"; + @SerializedName(SERIALIZED_NAME_SOME_PROPERTY) + private String someProperty; + + public InlineRequestBodyRequestContent() { + } + + public InlineRequestBodyRequestContent someProperty(String someProperty) { + + this.someProperty = someProperty; + return this; + } + + /** + * Get someProperty + * @return someProperty + **/ + @javax.annotation.Nonnull + public String getSomeProperty() { + return someProperty; + } + + + public void setSomeProperty(String someProperty) { + this.someProperty = someProperty; + } -import test.test.runtime.ApiException; -import test.test.runtime.Pair; -import java.net.URI; -import java.util.Map; -import java.util.List; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + InlineRequestBodyRequestContent inlineRequestBodyRequestContent = (InlineRequestBodyRequestContent) o; + return Objects.equals(this.someProperty, inlineRequestBodyRequestContent.someProperty); + + } -public class HttpBearerAuth implements Authentication { - private final String scheme; - private String bearerToken; + @Override + public int hashCode() { + return Objects.hash(someProperty); + } - public HttpBearerAuth(String scheme) { - this.scheme = scheme; + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineRequestBodyRequestContent {\\n"); + sb.append(" someProperty: ").append(toIndentedString(someProperty)).append("\\n"); + sb.append("}"); + return sb.toString(); } /** - * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. - * - * @return The bearer token + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). */ - public String getBearerToken() { - return bearerToken; + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\\n", "\\n "); } - /** - * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. - * - * @param bearerToken The bearer token to send in the Authorization header - */ - public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("someProperty"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("someProperty"); } - @Override - public void applyToParams(List queryParams, Map headerParams, Map cookieParams, - String payload, String method, URI uri) throws ApiException { - if (bearerToken == null) { - return; + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to InlineRequestBodyRequestContent + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!InlineRequestBodyRequestContent.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in InlineRequestBodyRequestContent is not found in the empty JSON string", InlineRequestBodyRequestContent.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!InlineRequestBodyRequestContent.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineRequestBodyRequestContent\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : InlineRequestBodyRequestContent.openapiRequiredFields) { + if (jsonObj.get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field \`%s\` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + } + } + if (!jsonObj.get("someProperty").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`someProperty\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("someProperty").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!InlineRequestBodyRequestContent.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'InlineRequestBodyRequestContent' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(InlineRequestBodyRequestContent.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, InlineRequestBodyRequestContent value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public InlineRequestBodyRequestContent read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); } + } - headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + /** + * Create an instance of InlineRequestBodyRequestContent given an JSON string + * + * @param jsonString JSON string + * @return An instance of InlineRequestBodyRequestContent + * @throws IOException if the JSON string is invalid with respect to InlineRequestBodyRequestContent + */ + public static InlineRequestBodyRequestContent fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, InlineRequestBodyRequestContent.class); } - private static String upperCaseBearer(String scheme) { - return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + /** + * Convert an instance of InlineRequestBodyRequestContent to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); } } ", - "src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java": "/* + "src/main/java/test/test/runtime/model/MyEnum.java": "/* * Edge Cases * * @@ -37150,142 +40550,109 @@ public class HttpBearerAuth implements Authentication { package test.test.runtime.model; -import test.test.runtime.ApiException; import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; import java.util.Map; -import javax.ws.rs.core.GenericType; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; -//import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; /** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + * Gets or Sets MyEnum */ -@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map getSchemas(); +@JsonAdapter(MyEnum.Adapter.class) +public enum MyEnum { - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} + ONE("one"), - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} + TWO("two"), - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } + THREE("three"); - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } + private String value; - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } + MyEnum(String value) { + this.value = value; + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\\n"); - sb.append("}"); - return sb.toString(); - } + public String getValue() { + return value; + } - /** - * 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 "); - } + @Override + public String toString() { + return String.valueOf(value); + } - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); + public static MyEnum fromValue(String value) { + for (MyEnum b : MyEnum.values()) { + if (b.value.equals(value)) { + return b; + } } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + public static class Adapter extends TypeAdapter { @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); + public void write(final JsonWriter jsonWriter, final MyEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); } - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } + @Override + public MyEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return MyEnum.fromValue(value); } - - - + } } ", - "src/main/java/test/test/runtime/model/InlineEnum200Response.java": "/* + "src/main/java/test/test/runtime/model/NamedOneOf.java": "/* * Edge Cases * * @@ -37301,7 +40668,6 @@ package test.test.runtime.model; import java.util.Objects; import java.util.Arrays; -import test.test.runtime.model.InlineEnum200ResponseCategoryEnum; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; @@ -37353,35 +40719,35 @@ import com.google.gson.JsonParseException; import test.test.runtime.JSON; /** - * InlineEnum200Response + * NamedOneOf */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder -public class InlineEnum200Response { - public static final String SERIALIZED_NAME_CATEGORY = "category"; - @SerializedName(SERIALIZED_NAME_CATEGORY) - private InlineEnum200ResponseCategoryEnum category; +public class NamedOneOf { + public static final String SERIALIZED_NAME_FOO = "foo"; + @SerializedName(SERIALIZED_NAME_FOO) + private String foo; - public InlineEnum200Response() { + public NamedOneOf() { } - public InlineEnum200Response category(InlineEnum200ResponseCategoryEnum category) { + public NamedOneOf foo(String foo) { - this.category = category; + this.foo = foo; return this; } /** - * Get category - * @return category + * Get foo + * @return foo **/ @javax.annotation.Nullable - public InlineEnum200ResponseCategoryEnum getCategory() { - return category; + public String getFoo() { + return foo; } - public void setCategory(InlineEnum200ResponseCategoryEnum category) { - this.category = category; + public void setFoo(String foo) { + this.foo = foo; } @@ -37393,21 +40759,21 @@ public class InlineEnum200Response { if (o == null || getClass() != o.getClass()) { return false; } - InlineEnum200Response inlineEnum200Response = (InlineEnum200Response) o; - return Objects.equals(this.category, inlineEnum200Response.category); + NamedOneOf namedOneOf = (NamedOneOf) o; + return Objects.equals(this.foo, namedOneOf.foo); } @Override public int hashCode() { - return Objects.hash(category); + return Objects.hash(foo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class InlineEnum200Response {\\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\\n"); + sb.append("class NamedOneOf {\\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -37430,7 +40796,7 @@ public class InlineEnum200Response { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("category"); + openapiFields.add("foo"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); @@ -37440,25 +40806,24 @@ public class InlineEnum200Response { * Validates the JSON Object and throws an exception if issues found * * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to InlineEnum200Response + * @throws IOException if the JSON Object is invalid with respect to NamedOneOf */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!InlineEnum200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in InlineEnum200Response is not found in the empty JSON string", InlineEnum200Response.openapiRequiredFields.toString())); + if (!NamedOneOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in NamedOneOf is not found in the empty JSON string", NamedOneOf.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!InlineEnum200Response.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineEnum200Response\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!NamedOneOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`NamedOneOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - // validate the optional field \`category\` - if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { - InlineEnum200ResponseCategoryEnum.validateJsonObject(jsonObj.getAsJsonObject("category")); + if ((jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonNull()) && !jsonObj.get("foo").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`foo\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("foo").toString())); } } @@ -37466,22 +40831,22 @@ public class InlineEnum200Response { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!InlineEnum200Response.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'InlineEnum200Response' and its subtypes + if (!NamedOneOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NamedOneOf' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(InlineEnum200Response.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NamedOneOf.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, InlineEnum200Response value) throws IOException { + public void write(JsonWriter out, NamedOneOf value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public InlineEnum200Response read(JsonReader in) throws IOException { + public NamedOneOf read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -37492,18 +40857,18 @@ public class InlineEnum200Response { } /** - * Create an instance of InlineEnum200Response given an JSON string + * Create an instance of NamedOneOf given an JSON string * * @param jsonString JSON string - * @return An instance of InlineEnum200Response - * @throws IOException if the JSON string is invalid with respect to InlineEnum200Response + * @return An instance of NamedOneOf + * @throws IOException if the JSON string is invalid with respect to NamedOneOf */ - public static InlineEnum200Response fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, InlineEnum200Response.class); + public static NamedOneOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NamedOneOf.class); } /** - * Convert an instance of InlineEnum200Response to an JSON string + * Convert an instance of NamedOneOf to an JSON string * * @return JSON string */ @@ -37512,7 +40877,7 @@ public class InlineEnum200Response { } } ", - "src/main/java/test/test/runtime/model/InlineEnum200ResponseCategoryEnum.java": "/* + "src/main/java/test/test/runtime/model/NamedOneOfUnion.java": "/* * Edge Cases * * @@ -37528,6 +40893,8 @@ package test.test.runtime.model; import java.util.Objects; import java.util.Arrays; +import test.test.runtime.model.AnotherNamedOneOf; +import test.test.runtime.model.NamedOneOf; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; @@ -37578,55 +40945,233 @@ import com.google.gson.JsonParseException; import test.test.runtime.JSON; -/** - * Gets or Sets InlineEnum200ResponseCategoryEnum - */ -@JsonAdapter(InlineEnum200ResponseCategoryEnum.Adapter.class) -public enum InlineEnum200ResponseCategoryEnum { +@lombok.experimental.SuperBuilder +public class NamedOneOfUnion extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(NamedOneOfUnion.class.getName()); - FRUIT("fruit"), + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NamedOneOfUnion.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NamedOneOfUnion' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterNamedOneOf = gson.getDelegateAdapter(this, TypeToken.get(NamedOneOf.class)); + final TypeAdapter adapterAnotherNamedOneOf = gson.getDelegateAdapter(this, TypeToken.get(AnotherNamedOneOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NamedOneOfUnion value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`NamedOneOf\` + if (value.getActualInstance() instanceof NamedOneOf) { + JsonObject obj = adapterNamedOneOf.toJsonTree((NamedOneOf)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`AnotherNamedOneOf\` + if (value.getActualInstance() instanceof AnotherNamedOneOf) { + JsonObject obj = adapterAnotherNamedOneOf.toJsonTree((AnotherNamedOneOf)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: NamedOneOf, AnotherNamedOneOf"); + } + + @Override + public NamedOneOfUnion read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize NamedOneOf + try { + // validate the JSON object to see if any exception is thrown + NamedOneOf.validateJsonObject(jsonObject); + actualAdapter = adapterNamedOneOf; + match++; + log.log(Level.FINER, "Input data matches schema 'NamedOneOf'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for NamedOneOf failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'NamedOneOf'", e); + } + + // deserialize AnotherNamedOneOf + try { + // validate the JSON object to see if any exception is thrown + AnotherNamedOneOf.validateJsonObject(jsonObject); + actualAdapter = adapterAnotherNamedOneOf; + match++; + log.log(Level.FINER, "Input data matches schema 'AnotherNamedOneOf'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for AnotherNamedOneOf failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'AnotherNamedOneOf'", e); + } + + if (match == 1) { + NamedOneOfUnion ret = new NamedOneOfUnion(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for NamedOneOfUnion: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public NamedOneOfUnion() { + super("oneOf", Boolean.FALSE); + } + + public NamedOneOfUnion(NamedOneOf o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public NamedOneOfUnion(AnotherNamedOneOf o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("NamedOneOf", new GenericType() { + }); + schemas.put("AnotherNamedOneOf", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return NamedOneOfUnion.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * NamedOneOf, AnotherNamedOneOf + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof NamedOneOf) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof AnotherNamedOneOf) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be NamedOneOf, AnotherNamedOneOf"); + } + + /** + * Get the actual instance, which can be the following: + * NamedOneOf, AnotherNamedOneOf + * + * @return The actual instance (NamedOneOf, AnotherNamedOneOf) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } - VEGETABLE("vegetable"); + /** + * Get the actual instance of \`NamedOneOf\`. If the actual instance is not \`NamedOneOf\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`NamedOneOf\` + * @throws ClassCastException if the instance is not \`NamedOneOf\` + */ + public NamedOneOf getNamedOneOf() throws ClassCastException { + return (NamedOneOf)super.getActualInstance(); + } - private String value; + /** + * Get the actual instance of \`AnotherNamedOneOf\`. If the actual instance is not \`AnotherNamedOneOf\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`AnotherNamedOneOf\` + * @throws ClassCastException if the instance is not \`AnotherNamedOneOf\` + */ + public AnotherNamedOneOf getAnotherNamedOneOf() throws ClassCastException { + return (AnotherNamedOneOf)super.getActualInstance(); + } - InlineEnum200ResponseCategoryEnum(String value) { - this.value = value; - } - public String getValue() { - return value; + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to NamedOneOfUnion + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + // validate oneOf schemas one by one + int validCount = 0; + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with NamedOneOf + try { + NamedOneOf.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for NamedOneOf failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with AnotherNamedOneOf + try { + AnotherNamedOneOf.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for AnotherNamedOneOf failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString())); + } } - @Override - public String toString() { - return String.valueOf(value); + /** + * Create an instance of NamedOneOfUnion given an JSON string + * + * @param jsonString JSON string + * @return An instance of NamedOneOfUnion + * @throws IOException if the JSON string is invalid with respect to NamedOneOfUnion + */ + public static NamedOneOfUnion fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NamedOneOfUnion.class); } - public static InlineEnum200ResponseCategoryEnum fromValue(String value) { - for (InlineEnum200ResponseCategoryEnum b : InlineEnum200ResponseCategoryEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); + /** + * Convert an instance of NamedOneOfUnion to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); } - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final InlineEnum200ResponseCategoryEnum enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public InlineEnum200ResponseCategoryEnum read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return InlineEnum200ResponseCategoryEnum.fromValue(value); - } - } } ", - "src/main/java/test/test/runtime/model/InlineRequestBodyRequestContent.java": "/* + "src/main/java/test/test/runtime/model/SomeObject.java": "/* * Edge Cases * * @@ -37693,35 +41238,35 @@ import com.google.gson.JsonParseException; import test.test.runtime.JSON; /** - * InlineRequestBodyRequestContent + * SomeObject */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder -public class InlineRequestBodyRequestContent { - public static final String SERIALIZED_NAME_SOME_PROPERTY = "someProperty"; - @SerializedName(SERIALIZED_NAME_SOME_PROPERTY) - private String someProperty; +public class SomeObject { + public static final String SERIALIZED_NAME_A = "a"; + @SerializedName(SERIALIZED_NAME_A) + private String a; - public InlineRequestBodyRequestContent() { + public SomeObject() { } - public InlineRequestBodyRequestContent someProperty(String someProperty) { + public SomeObject a(String a) { - this.someProperty = someProperty; + this.a = a; return this; } /** - * Get someProperty - * @return someProperty + * Get a + * @return a **/ - @javax.annotation.Nonnull - public String getSomeProperty() { - return someProperty; + @javax.annotation.Nullable + public String getA() { + return a; } - public void setSomeProperty(String someProperty) { - this.someProperty = someProperty; + public void setA(String a) { + this.a = a; } @@ -37733,21 +41278,21 @@ public class InlineRequestBodyRequestContent { if (o == null || getClass() != o.getClass()) { return false; } - InlineRequestBodyRequestContent inlineRequestBodyRequestContent = (InlineRequestBodyRequestContent) o; - return Objects.equals(this.someProperty, inlineRequestBodyRequestContent.someProperty); + SomeObject someObject = (SomeObject) o; + return Objects.equals(this.a, someObject.a); } @Override public int hashCode() { - return Objects.hash(someProperty); + return Objects.hash(a); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class InlineRequestBodyRequestContent {\\n"); - sb.append(" someProperty: ").append(toIndentedString(someProperty)).append("\\n"); + sb.append("class SomeObject {\\n"); + sb.append(" a: ").append(toIndentedString(a)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -37770,42 +41315,34 @@ public class InlineRequestBodyRequestContent { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("someProperty"); + openapiFields.add("a"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("someProperty"); } /** * Validates the JSON Object and throws an exception if issues found * * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to InlineRequestBodyRequestContent + * @throws IOException if the JSON Object is invalid with respect to SomeObject */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!InlineRequestBodyRequestContent.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in InlineRequestBodyRequestContent is not found in the empty JSON string", InlineRequestBodyRequestContent.openapiRequiredFields.toString())); + if (!SomeObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in SomeObject is not found in the empty JSON string", SomeObject.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!InlineRequestBodyRequestContent.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineRequestBodyRequestContent\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : InlineRequestBodyRequestContent.openapiRequiredFields) { - if (jsonObj.get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field \`%s\` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + if (!SomeObject.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`SomeObject\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (!jsonObj.get("someProperty").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`someProperty\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("someProperty").toString())); + if ((jsonObj.get("a") != null && !jsonObj.get("a").isJsonNull()) && !jsonObj.get("a").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`a\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("a").toString())); } } @@ -37813,22 +41350,22 @@ public class InlineRequestBodyRequestContent { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!InlineRequestBodyRequestContent.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'InlineRequestBodyRequestContent' and its subtypes + if (!SomeObject.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'SomeObject' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(InlineRequestBodyRequestContent.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(SomeObject.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, InlineRequestBodyRequestContent value) throws IOException { + public void write(JsonWriter out, SomeObject value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public InlineRequestBodyRequestContent read(JsonReader in) throws IOException { + public SomeObject read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -37839,18 +41376,18 @@ public class InlineRequestBodyRequestContent { } /** - * Create an instance of InlineRequestBodyRequestContent given an JSON string + * Create an instance of SomeObject given an JSON string * * @param jsonString JSON string - * @return An instance of InlineRequestBodyRequestContent - * @throws IOException if the JSON string is invalid with respect to InlineRequestBodyRequestContent + * @return An instance of SomeObject + * @throws IOException if the JSON string is invalid with respect to SomeObject */ - public static InlineRequestBodyRequestContent fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, InlineRequestBodyRequestContent.class); + public static SomeObject fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, SomeObject.class); } /** - * Convert an instance of InlineRequestBodyRequestContent to an JSON string + * Convert an instance of SomeObject to an JSON string * * @return JSON string */ @@ -37858,122 +41395,6 @@ public class InlineRequestBodyRequestContent { return JSON.getGson().toJson(this); } } -", - "src/main/java/test/test/runtime/model/MyEnum.java": "/* - * Edge Cases - * - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated. - * Do not edit the class manually. - */ - - -package test.test.runtime.model; - -import java.util.Objects; -import java.util.Arrays; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import javax.ws.rs.core.GenericType; - -import java.io.IOException; -import java.io.File; -import java.math.BigDecimal; -import java.net.URI; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.util.UUID; -import java.lang.reflect.Type; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.List; -import java.util.Set; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.JsonPrimitive; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; - -import test.test.runtime.JSON; - -/** - * Gets or Sets MyEnum - */ -@JsonAdapter(MyEnum.Adapter.class) -public enum MyEnum { - - ONE("one"), - - TWO("two"), - - THREE("three"); - - private String value; - - MyEnum(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static MyEnum fromValue(String value) { - for (MyEnum b : MyEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final MyEnum enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public MyEnum read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return MyEnum.fromValue(value); - } - } -} ", } `; diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap index 76f476dfd..09e6756cc 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap @@ -17428,10 +17428,17 @@ test_project/__init__.py test_project/py.typed test_project/rest.py docs/DefaultApi.md +docs/AdditionalPropertiesResponse.md +docs/AnotherNamedOneOf.md +docs/ArrayOfOneOfs.md +docs/Dictionary.md docs/InlineEnum200Response.md docs/InlineEnum200ResponseCategoryEnum.md docs/InlineRequestBodyRequestContent.md docs/MyEnum.md +docs/NamedOneOf.md +docs/NamedOneOfUnion.md +docs/SomeObject.md README.md test_project/interceptors/try_catch.py test_project/interceptors/response_headers.py @@ -17444,10 +17451,17 @@ test_project/response.py test_project/api/default_api.py test_project/api/__init__.py test_project/models/__init__.py +test_project/models/additional_properties_response.py +test_project/models/another_named_one_of.py +test_project/models/array_of_one_ofs.py +test_project/models/dictionary.py test_project/models/inline_enum200_response.py test_project/models/inline_enum200_response_category_enum.py test_project/models/inline_request_body_request_content.py -test_project/models/my_enum.py", +test_project/models/my_enum.py +test_project/models/named_one_of.py +test_project/models/named_one_of_union.py +test_project/models/some_object.py", "README.md": "# Edge Cases @@ -17479,47 +17493,185 @@ configuration = test_project.Configuration( with test_project.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = test_project.DefaultApi(api_client) - my_string_array_request_params = [] # List[str] | (optional) - my_enum_array_request_params = [] # List[MyEnum] | (optional) - my_integer_array_request_params = [2436284417048576,6600606720458752,2769288930787328] # List[int] | (optional) - my_long_array_request_params = [3479256564760576,857015102472192,5661035377721344] # List[int] | (optional) - my_int32_array_request_params = [] # List[int] | (optional) - my_number_array_request_params = [0.1599486346822232,0.4432248624507338,0.8626475473865867] # List[float] | (optional) - my_float_array_request_params = [0.7941185790114105,0.005342561984434724,0.36126157245598733] # List[float] | (optional) - my_double_array_request_params = [0.3810686601791531] # List[float] | (optional) - my_enum_request_param = test_project.MyEnum() # MyEnum | (optional) try: - api_instance.array_request_parameters(my_string_array_request_params=my_string_array_request_params, my_enum_array_request_params=my_enum_array_request_params, my_integer_array_request_params=my_integer_array_request_params, my_long_array_request_params=my_long_array_request_params, my_int32_array_request_params=my_int32_array_request_params, my_number_array_request_params=my_number_array_request_params, my_float_array_request_params=my_float_array_request_params, my_double_array_request_params=my_double_array_request_params, my_enum_request_param=my_enum_request_param) + api_response = api_instance.array_of_one_ofs() + print("The response of DefaultApi->array_of_one_ofs:\\n") + pprint(api_response) except ApiException as e: - print("Exception when calling DefaultApi->array_request_parameters: %s\\n" % e) + print("Exception when calling DefaultApi->array_of_one_ofs: %s\\n" % e) \`\`\` ## Documentation for API Endpoints Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**array_of_one_ofs**](docs/DefaultApi.md#array_of_one_ofs) | **POST** /array-of-one-ofs | *DefaultApi* | [**array_request_parameters**](docs/DefaultApi.md#array_request_parameters) | **GET** /array-request-parameters | +*DefaultApi* | [**dictionary**](docs/DefaultApi.md#dictionary) | **POST** /additional-properties | *DefaultApi* | [**inline_enum**](docs/DefaultApi.md#inline_enum) | **GET** /inline-enum | *DefaultApi* | [**inline_request_body**](docs/DefaultApi.md#inline_request_body) | **POST** /inline-request-body | +*DefaultApi* | [**named_one_of**](docs/DefaultApi.md#named_one_of) | **POST** /named-one-of | *DefaultApi* | [**reserved_keywords**](docs/DefaultApi.md#reserved_keywords) | **GET** /reserved-keywords | ## Documentation For Models + - [AdditionalPropertiesResponse](docs/AdditionalPropertiesResponse.md) + - [AnotherNamedOneOf](docs/AnotherNamedOneOf.md) + - [ArrayOfOneOfs](docs/ArrayOfOneOfs.md) + - [Dictionary](docs/Dictionary.md) - [InlineEnum200Response](docs/InlineEnum200Response.md) - [InlineEnum200ResponseCategoryEnum](docs/InlineEnum200ResponseCategoryEnum.md) - [InlineRequestBodyRequestContent](docs/InlineRequestBodyRequestContent.md) - [MyEnum](docs/MyEnum.md) + - [NamedOneOf](docs/NamedOneOf.md) + - [NamedOneOfUnion](docs/NamedOneOfUnion.md) + - [SomeObject](docs/SomeObject.md) +", + "docs/AdditionalPropertiesResponse.md": "# AdditionalPropertiesResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dictionary_of_objects** | [**Dictionary**](Dictionary.md) | | [optional] +**dictionary_of_primitives** | **Dict[str, str]** | | [optional] + +## Example + +\`\`\`python +from test_project.models.additional_properties_response import AdditionalPropertiesResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesResponse from a JSON string +additional_properties_response_instance = AdditionalPropertiesResponse.from_json(json) +# print the JSON string representation of the object +print(AdditionalPropertiesResponse.to_json()) + +# convert the object into a dict +additional_properties_response_dict = additional_properties_response_instance.to_dict() +# create an instance of AdditionalPropertiesResponse from a dict +additional_properties_response_form_dict = additional_properties_response.from_dict(additional_properties_response_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +", + "docs/AnotherNamedOneOf.md": "# AnotherNamedOneOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.another_named_one_of import AnotherNamedOneOf + +# TODO update the JSON string below +json = "{}" +# create an instance of AnotherNamedOneOf from a JSON string +another_named_one_of_instance = AnotherNamedOneOf.from_json(json) +# print the JSON string representation of the object +print(AnotherNamedOneOf.to_json()) + +# convert the object into a dict +another_named_one_of_dict = another_named_one_of_instance.to_dict() +# create an instance of AnotherNamedOneOf from a dict +another_named_one_of_form_dict = another_named_one_of.from_dict(another_named_one_of_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +", + "docs/ArrayOfOneOfs.md": "# ArrayOfOneOfs + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**one_ofs** | **List[NamedOneOfUnion]** | | [optional] + +## Example + +\`\`\`python +from test_project.models.array_of_one_ofs import ArrayOfOneOfs + +# TODO update the JSON string below +json = "{}" +# create an instance of ArrayOfOneOfs from a JSON string +array_of_one_ofs_instance = ArrayOfOneOfs.from_json(json) +# print the JSON string representation of the object +print(ArrayOfOneOfs.to_json()) + +# convert the object into a dict +array_of_one_ofs_dict = array_of_one_ofs_instance.to_dict() +# create an instance of ArrayOfOneOfs from a dict +array_of_one_ofs_form_dict = array_of_one_ofs.from_dict(array_of_one_ofs_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + ", "docs/DefaultApi.md": "# test_project.DefaultApi Method | HTTP request | Description ------------- | ------------- | ------------- +[**array_of_one_ofs**](DefaultApi.md#array_of_one_ofs) | **POST** /array-of-one-ofs | [**array_request_parameters**](DefaultApi.md#array_request_parameters) | **GET** /array-request-parameters | +[**dictionary**](DefaultApi.md#dictionary) | **POST** /additional-properties | [**inline_enum**](DefaultApi.md#inline_enum) | **GET** /inline-enum | [**inline_request_body**](DefaultApi.md#inline_request_body) | **POST** /inline-request-body | +[**named_one_of**](DefaultApi.md#named_one_of) | **POST** /named-one-of | [**reserved_keywords**](DefaultApi.md#reserved_keywords) | **GET** /reserved-keywords | +# **array_of_one_ofs** +> ArrayOfOneOfs array_of_one_ofs() + + +### Example + +\`\`\`python +import time +import test_project +from test_project.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = test_project.Configuration( + host = "http://localhost" +) + +# Enter a context with an instance of the API client +with test_project.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = test_project.DefaultApi(api_client) + + try: + api_response = api_instance.array_of_one_ofs() + print("The response of DefaultApi->array_of_one_ofs:\\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->array_of_one_ofs: %s\\n" % e) +\`\`\` + +### Parameters +This endpoint does not need any parameters. + +### Return type + +[**ArrayOfOneOfs**](ArrayOfOneOfs.md) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok | - | + +[[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) + # **array_request_parameters** > array_request_parameters(my_string_array_request_params=my_string_array_request_params, my_enum_array_request_params=my_enum_array_request_params, my_integer_array_request_params=my_integer_array_request_params, my_long_array_request_params=my_long_array_request_params, my_int32_array_request_params=my_int32_array_request_params, my_number_array_request_params=my_number_array_request_params, my_float_array_request_params=my_float_array_request_params, my_double_array_request_params=my_double_array_request_params, my_enum_request_param=my_enum_request_param) @@ -17587,6 +17739,56 @@ void (empty response body) [[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) +# **dictionary** +> AdditionalPropertiesResponse dictionary() + + +### Example + +\`\`\`python +import time +import test_project +from test_project.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = test_project.Configuration( + host = "http://localhost" +) + +# Enter a context with an instance of the API client +with test_project.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = test_project.DefaultApi(api_client) + + try: + api_response = api_instance.dictionary() + print("The response of DefaultApi->dictionary:\\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->dictionary: %s\\n" % e) +\`\`\` + +### Parameters +This endpoint does not need any parameters. + +### Return type + +[**AdditionalPropertiesResponse**](AdditionalPropertiesResponse.md) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok | - | + +[[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) + # **inline_enum** > InlineEnum200Response inline_enum() @@ -17688,6 +17890,56 @@ void (empty response body) [[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) +# **named_one_of** +> NamedOneOfUnion named_one_of() + + +### Example + +\`\`\`python +import time +import test_project +from test_project.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = test_project.Configuration( + host = "http://localhost" +) + +# Enter a context with an instance of the API client +with test_project.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = test_project.DefaultApi(api_client) + + try: + api_response = api_instance.named_one_of() + print("The response of DefaultApi->named_one_of:\\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->named_one_of: %s\\n" % e) +\`\`\` + +### Parameters +This endpoint does not need any parameters. + +### Return type + +[**NamedOneOfUnion**](NamedOneOfUnion.md) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok | - | + +[[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) + # **reserved_keywords** > reserved_keywords(var_with=var_with, var_if=var_if, var_class=var_class) @@ -17743,6 +17995,32 @@ void (empty response body) [[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) +", + "docs/Dictionary.md": "# Dictionary + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +\`\`\`python +from test_project.models.dictionary import Dictionary + +# TODO update the JSON string below +json = "{}" +# create an instance of Dictionary from a JSON string +dictionary_instance = Dictionary.from_json(json) +# print the JSON string representation of the object +print(Dictionary.to_json()) + +# convert the object into a dict +dictionary_dict = dictionary_instance.to_dict() +# create an instance of Dictionary from a dict +dictionary_form_dict = dictionary.from_dict(dictionary_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + ", "docs/InlineEnum200Response.md": "# InlineEnum200Response @@ -17816,40 +18094,125 @@ 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) ", - "poetry.toml": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". + "docs/NamedOneOf.md": "# NamedOneOf -[repositories.testpypi] -url = "https://test.pypi.org/legacy/" -", - "pyproject.toml": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **str** | | [optional] -[tool.poetry] -name = "test_project" -version = "1.0.0" -description = "" -authors = [ "test " ] -readme = "README.md" -include = [ "test_project", "test_project/**/*.py" ] +## Example - [[tool.poetry.packages]] - include = "test_project" +\`\`\`python +from test_project.models.named_one_of import NamedOneOf - [tool.poetry.dependencies] - aenum = "^3.1.11" - pydantic = "^2.5.2" - python-dateutil = "~2.8.2" - python = "^3.9" - urllib3 = "~1.26.7" +# TODO update the JSON string below +json = "{}" +# create an instance of NamedOneOf from a JSON string +named_one_of_instance = NamedOneOf.from_json(json) +# print the JSON string representation of the object +print(NamedOneOf.to_json()) - [tool.poetry.dependencies.aws-lambda-powertools] - extras = [ "tracer", "aws-sdk" ] - version = "^2.28.0" +# convert the object into a dict +named_one_of_dict = named_one_of_instance.to_dict() +# create an instance of NamedOneOf from a dict +named_one_of_form_dict = named_one_of.from_dict(named_one_of_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) -[tool.poetry.group.dev.dependencies] -projen = "99.99.99" +", + "docs/NamedOneOfUnion.md": "# NamedOneOfUnion -[build-system] -requires = [ "poetry-core" ] +## Composed Of + +This model can be set to one of the following types: + +Type | Description | Notes +------------- | ------------- | ------------- +[**NamedOneOf**](NamedOneOf.md) | +[**AnotherNamedOneOf**](AnotherNamedOneOf.md) | + +## Example + +\`\`\`python +from test_project.models.named_one_of_union import NamedOneOfUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of NamedOneOfUnion from a JSON string +named_one_of_union_instance = NamedOneOfUnion.from_json(json) +# print the JSON string representation of the object +print(NamedOneOfUnion.to_json()) + +# convert the object into a dict +named_one_of_union_dict = named_one_of_union_instance.to_dict() +# create an instance of NamedOneOfUnion from a dict +named_one_of_union_form_dict = named_one_of_union.from_dict(named_one_of_union_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +", + "docs/SomeObject.md": "# SomeObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.some_object import SomeObject + +# TODO update the JSON string below +json = "{}" +# create an instance of SomeObject from a JSON string +some_object_instance = SomeObject.from_json(json) +# print the JSON string representation of the object +print(SomeObject.to_json()) + +# convert the object into a dict +some_object_dict = some_object_instance.to_dict() +# create an instance of SomeObject from a dict +some_object_form_dict = some_object.from_dict(some_object_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +", + "poetry.toml": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". + +[repositories.testpypi] +url = "https://test.pypi.org/legacy/" +", + "pyproject.toml": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". + +[tool.poetry] +name = "test_project" +version = "1.0.0" +description = "" +authors = [ "test " ] +readme = "README.md" +include = [ "test_project", "test_project/**/*.py" ] + + [[tool.poetry.packages]] + include = "test_project" + + [tool.poetry.dependencies] + aenum = "^3.1.11" + pydantic = "^2.5.2" + python-dateutil = "~2.8.2" + python = "^3.9" + urllib3 = "~1.26.7" + + [tool.poetry.dependencies.aws-lambda-powertools] + extras = [ "tracer", "aws-sdk" ] + version = "^2.28.0" + +[tool.poetry.group.dev.dependencies] +projen = "99.99.99" + +[build-system] +requires = [ "poetry-core" ] build-backend = "poetry.core.masonry.api" ", "test_project/__init__.py": "# coding: utf-8 @@ -17884,10 +18247,17 @@ from test_project.exceptions import ApiAttributeError from test_project.exceptions import ApiException # import models into sdk package +from test_project.models.additional_properties_response import AdditionalPropertiesResponse +from test_project.models.another_named_one_of import AnotherNamedOneOf +from test_project.models.array_of_one_ofs import ArrayOfOneOfs +from test_project.models.dictionary import Dictionary from test_project.models.inline_enum200_response import InlineEnum200Response from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent from test_project.models.my_enum import MyEnum +from test_project.models.named_one_of import NamedOneOf +from test_project.models.named_one_of_union import NamedOneOfUnion +from test_project.models.some_object import SomeObject ", "test_project/api/__init__.py": "# flake8: noqa @@ -17918,9 +18288,12 @@ try: except ImportError: from typing_extensions import Annotated +from test_project.models.additional_properties_response import AdditionalPropertiesResponse +from test_project.models.array_of_one_ofs import ArrayOfOneOfs from test_project.models.inline_enum200_response import InlineEnum200Response from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent from test_project.models.my_enum import MyEnum +from test_project.models.named_one_of_union import NamedOneOfUnion from test_project.api_client import ApiClient from test_project.api_response import ApiResponse @@ -17939,17 +18312,8 @@ class DefaultApi: self.api_client = api_client @validate_call - def array_request_parameters( + def array_of_one_ofs( self, - my_string_array_request_params: Optional[List[StrictStr]] = None, - my_enum_array_request_params: Optional[List[MyEnum]] = None, - my_integer_array_request_params: Optional[List[StrictInt]] = None, - my_long_array_request_params: Optional[List[StrictInt]] = None, - my_int32_array_request_params: Optional[List[StrictInt]] = None, - my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -17962,26 +18326,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> None: - """array_request_parameters - :param my_string_array_request_params: (optional) - :type my_string_array_request_params: List[str], optional - :param my_enum_array_request_params: (optional) - :type my_enum_array_request_params: List[MyEnum], optional - :param my_integer_array_request_params: (optional) - :type my_integer_array_request_params: List[int], optional - :param my_long_array_request_params: (optional) - :type my_long_array_request_params: List[int], optional - :param my_int32_array_request_params: (optional) - :type my_int32_array_request_params: List[int], optional - :param my_number_array_request_params: (optional) - :type my_number_array_request_params: List[float], optional - :param my_float_array_request_params: (optional) - :type my_float_array_request_params: List[float], optional - :param my_double_array_request_params: (optional) - :type my_double_array_request_params: List[float], optional - :param my_enum_request_param: (optional) - :type my_enum_request_param: MyEnum, optional + ) -> ArrayOfOneOfs: + """array_of_one_ofs :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 @@ -18004,16 +18350,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._array_request_parameters_serialize( - my_string_array_request_params=my_string_array_request_params, - my_enum_array_request_params=my_enum_array_request_params, - my_integer_array_request_params=my_integer_array_request_params, - my_long_array_request_params=my_long_array_request_params, - my_int32_array_request_params=my_int32_array_request_params, - my_number_array_request_params=my_number_array_request_params, - my_float_array_request_params=my_float_array_request_params, - my_double_array_request_params=my_double_array_request_params, - my_enum_request_param=my_enum_request_param, + _param = self._array_of_one_ofs_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18021,6 +18358,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "ArrayOfOneOfs" } response_data = self.api_client.call_api( @@ -18035,17 +18373,8 @@ class DefaultApi: @validate_call - def array_request_parameters_with_http_info( + def array_of_one_ofs_with_http_info( self, - my_string_array_request_params: Optional[List[StrictStr]] = None, - my_enum_array_request_params: Optional[List[MyEnum]] = None, - my_integer_array_request_params: Optional[List[StrictInt]] = None, - my_long_array_request_params: Optional[List[StrictInt]] = None, - my_int32_array_request_params: Optional[List[StrictInt]] = None, - my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18058,26 +18387,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[None]: - """array_request_parameters - :param my_string_array_request_params: (optional) - :type my_string_array_request_params: List[str], optional - :param my_enum_array_request_params: (optional) - :type my_enum_array_request_params: List[MyEnum], optional - :param my_integer_array_request_params: (optional) - :type my_integer_array_request_params: List[int], optional - :param my_long_array_request_params: (optional) - :type my_long_array_request_params: List[int], optional - :param my_int32_array_request_params: (optional) - :type my_int32_array_request_params: List[int], optional - :param my_number_array_request_params: (optional) - :type my_number_array_request_params: List[float], optional - :param my_float_array_request_params: (optional) - :type my_float_array_request_params: List[float], optional - :param my_double_array_request_params: (optional) - :type my_double_array_request_params: List[float], optional - :param my_enum_request_param: (optional) - :type my_enum_request_param: MyEnum, optional + ) -> ApiResponse[ArrayOfOneOfs]: + """array_of_one_ofs :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 @@ -18100,16 +18411,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._array_request_parameters_serialize( - my_string_array_request_params=my_string_array_request_params, - my_enum_array_request_params=my_enum_array_request_params, - my_integer_array_request_params=my_integer_array_request_params, - my_long_array_request_params=my_long_array_request_params, - my_int32_array_request_params=my_int32_array_request_params, - my_number_array_request_params=my_number_array_request_params, - my_float_array_request_params=my_float_array_request_params, - my_double_array_request_params=my_double_array_request_params, - my_enum_request_param=my_enum_request_param, + _param = self._array_of_one_ofs_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18117,6 +18419,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "ArrayOfOneOfs" } response_data = self.api_client.call_api( @@ -18131,17 +18434,8 @@ class DefaultApi: @validate_call - def array_request_parameters_without_preload_content( + def array_of_one_ofs_without_preload_content( self, - my_string_array_request_params: Optional[List[StrictStr]] = None, - my_enum_array_request_params: Optional[List[MyEnum]] = None, - my_integer_array_request_params: Optional[List[StrictInt]] = None, - my_long_array_request_params: Optional[List[StrictInt]] = None, - my_int32_array_request_params: Optional[List[StrictInt]] = None, - my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18155,25 +18449,7 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """array_request_parameters - :param my_string_array_request_params: (optional) - :type my_string_array_request_params: List[str], optional - :param my_enum_array_request_params: (optional) - :type my_enum_array_request_params: List[MyEnum], optional - :param my_integer_array_request_params: (optional) - :type my_integer_array_request_params: List[int], optional - :param my_long_array_request_params: (optional) - :type my_long_array_request_params: List[int], optional - :param my_int32_array_request_params: (optional) - :type my_int32_array_request_params: List[int], optional - :param my_number_array_request_params: (optional) - :type my_number_array_request_params: List[float], optional - :param my_float_array_request_params: (optional) - :type my_float_array_request_params: List[float], optional - :param my_double_array_request_params: (optional) - :type my_double_array_request_params: List[float], optional - :param my_enum_request_param: (optional) - :type my_enum_request_param: MyEnum, optional + """array_of_one_ofs :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 @@ -18196,16 +18472,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._array_request_parameters_serialize( - my_string_array_request_params=my_string_array_request_params, - my_enum_array_request_params=my_enum_array_request_params, - my_integer_array_request_params=my_integer_array_request_params, - my_long_array_request_params=my_long_array_request_params, - my_int32_array_request_params=my_int32_array_request_params, - my_number_array_request_params=my_number_array_request_params, - my_float_array_request_params=my_float_array_request_params, - my_double_array_request_params=my_double_array_request_params, - my_enum_request_param=my_enum_request_param, + _param = self._array_of_one_ofs_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18213,6 +18480,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "ArrayOfOneOfs" } response_data = self.api_client.call_api( @@ -18222,17 +18490,8 @@ class DefaultApi: return response_data.response - def _array_request_parameters_serialize( + def _array_of_one_ofs_serialize( self, - my_string_array_request_params, - my_enum_array_request_params, - my_integer_array_request_params, - my_long_array_request_params, - my_int32_array_request_params, - my_number_array_request_params, - my_float_array_request_params, - my_double_array_request_params, - my_enum_request_param, _request_auth, _content_type, _headers, @@ -18242,14 +18501,6 @@ class DefaultApi: _host = None _collection_formats: Dict[str, str] = { - 'my-string-array-request-params': 'multi', - 'my-enum-array-request-params': 'multi', - 'my-integer-array-request-params': 'multi', - 'my-long-array-request-params': 'multi', - 'my-int32-array-request-params': 'multi', - 'my-number-array-request-params': 'multi', - 'my-float-array-request-params': 'multi', - 'my-double-array-request-params': 'multi', } _path_params: Dict[str, str] = {} @@ -18261,29 +18512,17 @@ class DefaultApi: # process the path parameters # process the query parameters - if my_string_array_request_params is not None: - _query_params.append(('my-string-array-request-params', my_string_array_request_params)) - if my_enum_array_request_params is not None: - _query_params.append(('my-enum-array-request-params', my_enum_array_request_params)) - if my_integer_array_request_params is not None: - _query_params.append(('my-integer-array-request-params', my_integer_array_request_params)) - if my_long_array_request_params is not None: - _query_params.append(('my-long-array-request-params', my_long_array_request_params)) - if my_int32_array_request_params is not None: - _query_params.append(('my-int32-array-request-params', my_int32_array_request_params)) - if my_number_array_request_params is not None: - _query_params.append(('my-number-array-request-params', my_number_array_request_params)) - if my_float_array_request_params is not None: - _query_params.append(('my-float-array-request-params', my_float_array_request_params)) - if my_double_array_request_params is not None: - _query_params.append(('my-double-array-request-params', my_double_array_request_params)) - if my_enum_request_param is not None: - _query_params.append(('my-enum-request-param', my_enum_request_param)) # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # authentication setting @@ -18291,8 +18530,8 @@ class DefaultApi: ] return self.api_client.param_serialize( - method='GET', - resource_path='/array-request-parameters', + method='POST', + resource_path='/array-of-one-ofs', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -18308,8 +18547,17 @@ class DefaultApi: @validate_call - def inline_enum( + def array_request_parameters( self, + my_string_array_request_params: Optional[List[StrictStr]] = None, + my_enum_array_request_params: Optional[List[MyEnum]] = None, + my_integer_array_request_params: Optional[List[StrictInt]] = None, + my_long_array_request_params: Optional[List[StrictInt]] = None, + my_int32_array_request_params: Optional[List[StrictInt]] = None, + my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18322,15 +18570,33 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> InlineEnum200Response: - """inline_enum - :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. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the + ) -> None: + """array_request_parameters + :param my_string_array_request_params: (optional) + :type my_string_array_request_params: List[str], optional + :param my_enum_array_request_params: (optional) + :type my_enum_array_request_params: List[MyEnum], optional + :param my_integer_array_request_params: (optional) + :type my_integer_array_request_params: List[int], optional + :param my_long_array_request_params: (optional) + :type my_long_array_request_params: List[int], optional + :param my_int32_array_request_params: (optional) + :type my_int32_array_request_params: List[int], optional + :param my_number_array_request_params: (optional) + :type my_number_array_request_params: List[float], optional + :param my_float_array_request_params: (optional) + :type my_float_array_request_params: List[float], optional + :param my_double_array_request_params: (optional) + :type my_double_array_request_params: List[float], optional + :param my_enum_request_param: (optional) + :type my_enum_request_param: MyEnum, optional + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :param _content_type: force content-type for the request. @@ -18346,7 +18612,16 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_enum_serialize( + _param = self._array_request_parameters_serialize( + my_string_array_request_params=my_string_array_request_params, + my_enum_array_request_params=my_enum_array_request_params, + my_integer_array_request_params=my_integer_array_request_params, + my_long_array_request_params=my_long_array_request_params, + my_int32_array_request_params=my_int32_array_request_params, + my_number_array_request_params=my_number_array_request_params, + my_float_array_request_params=my_float_array_request_params, + my_double_array_request_params=my_double_array_request_params, + my_enum_request_param=my_enum_request_param, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18354,7 +18629,6 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { - '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18369,8 +18643,17 @@ class DefaultApi: @validate_call - def inline_enum_with_http_info( + def array_request_parameters_with_http_info( self, + my_string_array_request_params: Optional[List[StrictStr]] = None, + my_enum_array_request_params: Optional[List[MyEnum]] = None, + my_integer_array_request_params: Optional[List[StrictInt]] = None, + my_long_array_request_params: Optional[List[StrictInt]] = None, + my_int32_array_request_params: Optional[List[StrictInt]] = None, + my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18383,8 +18666,26 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[InlineEnum200Response]: - """inline_enum + ) -> ApiResponse[None]: + """array_request_parameters + :param my_string_array_request_params: (optional) + :type my_string_array_request_params: List[str], optional + :param my_enum_array_request_params: (optional) + :type my_enum_array_request_params: List[MyEnum], optional + :param my_integer_array_request_params: (optional) + :type my_integer_array_request_params: List[int], optional + :param my_long_array_request_params: (optional) + :type my_long_array_request_params: List[int], optional + :param my_int32_array_request_params: (optional) + :type my_int32_array_request_params: List[int], optional + :param my_number_array_request_params: (optional) + :type my_number_array_request_params: List[float], optional + :param my_float_array_request_params: (optional) + :type my_float_array_request_params: List[float], optional + :param my_double_array_request_params: (optional) + :type my_double_array_request_params: List[float], optional + :param my_enum_request_param: (optional) + :type my_enum_request_param: MyEnum, optional :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 @@ -18407,7 +18708,16 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_enum_serialize( + _param = self._array_request_parameters_serialize( + my_string_array_request_params=my_string_array_request_params, + my_enum_array_request_params=my_enum_array_request_params, + my_integer_array_request_params=my_integer_array_request_params, + my_long_array_request_params=my_long_array_request_params, + my_int32_array_request_params=my_int32_array_request_params, + my_number_array_request_params=my_number_array_request_params, + my_float_array_request_params=my_float_array_request_params, + my_double_array_request_params=my_double_array_request_params, + my_enum_request_param=my_enum_request_param, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18415,7 +18725,6 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { - '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18430,8 +18739,17 @@ class DefaultApi: @validate_call - def inline_enum_without_preload_content( + def array_request_parameters_without_preload_content( self, + my_string_array_request_params: Optional[List[StrictStr]] = None, + my_enum_array_request_params: Optional[List[MyEnum]] = None, + my_integer_array_request_params: Optional[List[StrictInt]] = None, + my_long_array_request_params: Optional[List[StrictInt]] = None, + my_int32_array_request_params: Optional[List[StrictInt]] = None, + my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18445,7 +18763,25 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """inline_enum + """array_request_parameters + :param my_string_array_request_params: (optional) + :type my_string_array_request_params: List[str], optional + :param my_enum_array_request_params: (optional) + :type my_enum_array_request_params: List[MyEnum], optional + :param my_integer_array_request_params: (optional) + :type my_integer_array_request_params: List[int], optional + :param my_long_array_request_params: (optional) + :type my_long_array_request_params: List[int], optional + :param my_int32_array_request_params: (optional) + :type my_int32_array_request_params: List[int], optional + :param my_number_array_request_params: (optional) + :type my_number_array_request_params: List[float], optional + :param my_float_array_request_params: (optional) + :type my_float_array_request_params: List[float], optional + :param my_double_array_request_params: (optional) + :type my_double_array_request_params: List[float], optional + :param my_enum_request_param: (optional) + :type my_enum_request_param: MyEnum, optional :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 @@ -18468,7 +18804,16 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_enum_serialize( + _param = self._array_request_parameters_serialize( + my_string_array_request_params=my_string_array_request_params, + my_enum_array_request_params=my_enum_array_request_params, + my_integer_array_request_params=my_integer_array_request_params, + my_long_array_request_params=my_long_array_request_params, + my_int32_array_request_params=my_int32_array_request_params, + my_number_array_request_params=my_number_array_request_params, + my_float_array_request_params=my_float_array_request_params, + my_double_array_request_params=my_double_array_request_params, + my_enum_request_param=my_enum_request_param, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18476,7 +18821,6 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { - '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18486,8 +18830,17 @@ class DefaultApi: return response_data.response - def _inline_enum_serialize( + def _array_request_parameters_serialize( self, + my_string_array_request_params, + my_enum_array_request_params, + my_integer_array_request_params, + my_long_array_request_params, + my_int32_array_request_params, + my_number_array_request_params, + my_float_array_request_params, + my_double_array_request_params, + my_enum_request_param, _request_auth, _content_type, _headers, @@ -18497,6 +18850,14 @@ class DefaultApi: _host = None _collection_formats: Dict[str, str] = { + 'my-string-array-request-params': 'multi', + 'my-enum-array-request-params': 'multi', + 'my-integer-array-request-params': 'multi', + 'my-long-array-request-params': 'multi', + 'my-int32-array-request-params': 'multi', + 'my-number-array-request-params': 'multi', + 'my-float-array-request-params': 'multi', + 'my-double-array-request-params': 'multi', } _path_params: Dict[str, str] = {} @@ -18508,17 +18869,29 @@ class DefaultApi: # process the path parameters # process the query parameters + if my_string_array_request_params is not None: + _query_params.append(('my-string-array-request-params', my_string_array_request_params)) + if my_enum_array_request_params is not None: + _query_params.append(('my-enum-array-request-params', my_enum_array_request_params)) + if my_integer_array_request_params is not None: + _query_params.append(('my-integer-array-request-params', my_integer_array_request_params)) + if my_long_array_request_params is not None: + _query_params.append(('my-long-array-request-params', my_long_array_request_params)) + if my_int32_array_request_params is not None: + _query_params.append(('my-int32-array-request-params', my_int32_array_request_params)) + if my_number_array_request_params is not None: + _query_params.append(('my-number-array-request-params', my_number_array_request_params)) + if my_float_array_request_params is not None: + _query_params.append(('my-float-array-request-params', my_float_array_request_params)) + if my_double_array_request_params is not None: + _query_params.append(('my-double-array-request-params', my_double_array_request_params)) + if my_enum_request_param is not None: + _query_params.append(('my-enum-request-param', my_enum_request_param)) # process the header parameters # process the form parameters # process the body parameter - # set the HTTP header \`Accept\` - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) # authentication setting @@ -18527,7 +18900,7 @@ class DefaultApi: return self.api_client.param_serialize( method='GET', - resource_path='/inline-enum', + resource_path='/array-request-parameters', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -18543,9 +18916,8 @@ class DefaultApi: @validate_call - def inline_request_body( + def dictionary( self, - inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18558,10 +18930,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> None: - """inline_request_body - :param inline_request_body_request_content: (optional) - :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + ) -> AdditionalPropertiesResponse: + """dictionary :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 @@ -18584,8 +18954,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_request_body_serialize( - inline_request_body_request_content=inline_request_body_request_content, + _param = self._dictionary_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18593,6 +18962,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "AdditionalPropertiesResponse" } response_data = self.api_client.call_api( @@ -18607,9 +18977,8 @@ class DefaultApi: @validate_call - def inline_request_body_with_http_info( + def dictionary_with_http_info( self, - inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18622,10 +18991,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[None]: - """inline_request_body - :param inline_request_body_request_content: (optional) - :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + ) -> ApiResponse[AdditionalPropertiesResponse]: + """dictionary :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 @@ -18648,8 +19015,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_request_body_serialize( - inline_request_body_request_content=inline_request_body_request_content, + _param = self._dictionary_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18657,6 +19023,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "AdditionalPropertiesResponse" } response_data = self.api_client.call_api( @@ -18671,9 +19038,8 @@ class DefaultApi: @validate_call - def inline_request_body_without_preload_content( + def dictionary_without_preload_content( self, - inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18687,9 +19053,7 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """inline_request_body - :param inline_request_body_request_content: (optional) - :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + """dictionary :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 @@ -18712,8 +19076,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_request_body_serialize( - inline_request_body_request_content=inline_request_body_request_content, + _param = self._dictionary_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18721,6 +19084,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "AdditionalPropertiesResponse" } response_data = self.api_client.call_api( @@ -18730,9 +19094,8 @@ class DefaultApi: return response_data.response - def _inline_request_body_serialize( + def _dictionary_serialize( self, - inline_request_body_request_content, _request_auth, _content_type, _headers, @@ -18756,24 +19119,15 @@ class DefaultApi: # process the header parameters # process the form parameters # process the body parameter - if inline_request_body_request_content is not None: - _body_params = inline_request_body_request_content + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) - # set the HTTP header \`Content-Type\` - if _content_type: - _header_params['Content-Type'] = _content_type - else: - _default_content_type = ( - self.api_client.select_header_content_type( - [ - 'application/json' - ] - ) - ) - if _default_content_type is not None: - _header_params['Content-Type'] = _default_content_type # authentication setting _auth_settings: List[str] = [ @@ -18781,7 +19135,7 @@ class DefaultApi: return self.api_client.param_serialize( method='POST', - resource_path='/inline-request-body', + resource_path='/additional-properties', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -18797,11 +19151,8 @@ class DefaultApi: @validate_call - def reserved_keywords( + def inline_enum( self, - var_with: Optional[StrictStr] = None, - var_if: Optional[StrictStr] = None, - var_class: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18814,14 +19165,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> None: - """reserved_keywords - :param var_with: (optional) - :type var_with: str, optional - :param var_if: (optional) - :type var_if: str, optional - :param var_class: (optional) - :type var_class: str, optional + ) -> InlineEnum200Response: + """inline_enum :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 @@ -18844,10 +19189,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._reserved_keywords_serialize( - var_with=var_with, - var_if=var_if, - var_class=var_class, + _param = self._inline_enum_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18855,6 +19197,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18869,11 +19212,8 @@ class DefaultApi: @validate_call - def reserved_keywords_with_http_info( + def inline_enum_with_http_info( self, - var_with: Optional[StrictStr] = None, - var_if: Optional[StrictStr] = None, - var_class: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18886,14 +19226,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[None]: - """reserved_keywords - :param var_with: (optional) - :type var_with: str, optional - :param var_if: (optional) - :type var_if: str, optional - :param var_class: (optional) - :type var_class: str, optional + ) -> ApiResponse[InlineEnum200Response]: + """inline_enum :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 @@ -18916,10 +19250,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._reserved_keywords_serialize( - var_with=var_with, - var_if=var_if, - var_class=var_class, + _param = self._inline_enum_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18927,6 +19258,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18941,11 +19273,8 @@ class DefaultApi: @validate_call - def reserved_keywords_without_preload_content( + def inline_enum_without_preload_content( self, - var_with: Optional[StrictStr] = None, - var_if: Optional[StrictStr] = None, - var_class: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18959,13 +19288,7 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """reserved_keywords - :param var_with: (optional) - :type var_with: str, optional - :param var_if: (optional) - :type var_if: str, optional - :param var_class: (optional) - :type var_class: str, optional + """inline_enum :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 @@ -18988,10 +19311,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._reserved_keywords_serialize( - var_with=var_with, - var_if=var_if, - var_class=var_class, + _param = self._inline_enum_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18999,6 +19319,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -19008,11 +19329,8 @@ class DefaultApi: return response_data.response - def _reserved_keywords_serialize( + def _inline_enum_serialize( self, - var_with, - var_if, - var_class, _request_auth, _content_type, _headers, @@ -19033,17 +19351,17 @@ class DefaultApi: # process the path parameters # process the query parameters - if var_with is not None: - _query_params.append(('with', var_with)) - if var_if is not None: - _query_params.append(('if', var_if)) - if var_class is not None: - _query_params.append(('class', var_class)) # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # authentication setting @@ -19052,7 +19370,7 @@ class DefaultApi: return self.api_client.param_serialize( method='GET', - resource_path='/reserved-keywords', + resource_path='/inline-enum', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -19066,112 +19384,890 @@ class DefaultApi: ) -", - "test_project/api/operation_config.py": "from __future__ import annotations -import urllib.parse -import json -from typing import Callable, Any, Dict, List, NamedTuple, TypeVar, Generic, Union, TypedDict, Protocol, Optional, Literal, Annotated -from functools import wraps -from dataclasses import dataclass, fields -from datetime import datetime -import dateutil.parser -from pydantic import BaseModel, Field, StrictStr, conlist, StrictBool, StrictInt, StrictFloat - -from test_project.models import * - -T = TypeVar('T') -# Generic type for object keyed by operation names -@dataclass -class OperationConfig(Generic[T]): - array_request_parameters: T - inline_enum: T - inline_request_body: T - reserved_keywords: T - ... + @validate_call + def inline_request_body( + self, + inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """inline_request_body + :param inline_request_body_request_content: (optional) + :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 -# Look up path and http method for a given operation name -OperationLookup = { - "array_request_parameters": { - "path": "/array-request-parameters", - "method": "GET", - "contentTypes": ["application/json"] - }, - "inline_enum": { - "path": "/inline-enum", - "method": "GET", - "contentTypes": ["application/json"] - }, - "inline_request_body": { - "path": "/inline-request-body", - "method": "POST", - "contentTypes": ["application/json"] - }, - "reserved_keywords": { - "path": "/reserved-keywords", - "method": "GET", - "contentTypes": ["application/json"] - }, -} + _param = self._inline_request_body_serialize( + inline_request_body_request_content=inline_request_body_request_content, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) -class Operations: - @staticmethod - def all(value: T) -> OperationConfig[T]: - """ - Returns an OperationConfig with the same value for every operation - """ - return OperationConfig(**{ operation_id: value for operation_id, _ in OperationLookup.items() }) + _response_types_map: Dict[str, Optional[str]] = { + } -def uri_decode(value): - """ - URI decode a value or list of values - """ - if isinstance(value, list): - return [urllib.parse.unquote(v) for v in value] - return urllib.parse.unquote(value) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data -def decode_request_parameters(parameters): - """ - URI decode api request parameters (path, query or multi-value query) - """ - return { key: uri_decode(parameters[key]) if parameters[key] is not None else parameters[key] for key in parameters.keys() } -def parse_body(body, content_types, model): - """ - Parse the body of an api request into the given model if present - """ - if len([c for c in content_types if c != 'application/json']) == 0: - if model != Any: - body = model.model_validate(json.loads(body)) - else: - body = json.loads(body or '{}') - return body + @validate_call + def inline_request_body_with_http_info( + self, + inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """inline_request_body + :param inline_request_body_request_content: (optional) + :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 -def assert_required(required, base_name, parameters): - if required and parameters.get(base_name) is None: - raise Exception(f"Missing required request parameter '{base_name}'") + _param = self._inline_request_body_serialize( + inline_request_body_request_content=inline_request_body_request_content, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) -def coerce_float(base_name, s): - try: - return float(s) - except Exception as e: - raise Exception(f"Expected a number for request parameter '{base_name}'") + _response_types_map: Dict[str, Optional[str]] = { + } -def coerce_int(base_name, s): - try: - return int(s) - except Exception as e: - raise Exception(f"Expected an integer for request parameter '{base_name}'") + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) -def coerce_datetime(base_name, s): - try: - return dateutil.parser.parse(s) - except Exception as e: - raise Exception(f"Expected a valid date (iso format) for request parameter '{base_name}'") -def coerce_bool(base_name, s): - if s == "true": - return True + @validate_call + def inline_request_body_without_preload_content( + self, + inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """inline_request_body + :param inline_request_body_request_content: (optional) + :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._inline_request_body_serialize( + inline_request_body_request_content=inline_request_body_request_content, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _inline_request_body_serialize( + self, + inline_request_body_request_content, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if inline_request_body_request_content is not None: + _body_params = inline_request_body_request_content + + + + # set the HTTP header \`Content-Type\` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/inline-request-body', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + @validate_call + def named_one_of( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> NamedOneOfUnion: + """named_one_of + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._named_one_of_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "NamedOneOfUnion" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def named_one_of_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[NamedOneOfUnion]: + """named_one_of + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._named_one_of_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "NamedOneOfUnion" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def named_one_of_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """named_one_of + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._named_one_of_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "NamedOneOfUnion" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _named_one_of_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/named-one-of', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + @validate_call + def reserved_keywords( + self, + var_with: Optional[StrictStr] = None, + var_if: Optional[StrictStr] = None, + var_class: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """reserved_keywords + :param var_with: (optional) + :type var_with: str, optional + :param var_if: (optional) + :type var_if: str, optional + :param var_class: (optional) + :type var_class: str, optional + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._reserved_keywords_serialize( + var_with=var_with, + var_if=var_if, + var_class=var_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def reserved_keywords_with_http_info( + self, + var_with: Optional[StrictStr] = None, + var_if: Optional[StrictStr] = None, + var_class: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """reserved_keywords + :param var_with: (optional) + :type var_with: str, optional + :param var_if: (optional) + :type var_if: str, optional + :param var_class: (optional) + :type var_class: str, optional + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._reserved_keywords_serialize( + var_with=var_with, + var_if=var_if, + var_class=var_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def reserved_keywords_without_preload_content( + self, + var_with: Optional[StrictStr] = None, + var_if: Optional[StrictStr] = None, + var_class: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """reserved_keywords + :param var_with: (optional) + :type var_with: str, optional + :param var_if: (optional) + :type var_if: str, optional + :param var_class: (optional) + :type var_class: str, optional + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._reserved_keywords_serialize( + var_with=var_with, + var_if=var_if, + var_class=var_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _reserved_keywords_serialize( + self, + var_with, + var_if, + var_class, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if var_with is not None: + _query_params.append(('with', var_with)) + if var_if is not None: + _query_params.append(('if', var_if)) + if var_class is not None: + _query_params.append(('class', var_class)) + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/reserved-keywords', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + +", + "test_project/api/operation_config.py": "from __future__ import annotations +import urllib.parse +import json +from typing import Callable, Any, Dict, List, NamedTuple, TypeVar, Generic, Union, TypedDict, Protocol, Optional, Literal, Annotated +from functools import wraps +from dataclasses import dataclass, fields +from datetime import datetime +import dateutil.parser +from pydantic import BaseModel, Field, StrictStr, conlist, StrictBool, StrictInt, StrictFloat + +from test_project.models import * + +T = TypeVar('T') + +# Generic type for object keyed by operation names +@dataclass +class OperationConfig(Generic[T]): + array_of_one_ofs: T + array_request_parameters: T + dictionary: T + inline_enum: T + inline_request_body: T + named_one_of: T + reserved_keywords: T + ... + +# Look up path and http method for a given operation name +OperationLookup = { + "array_of_one_ofs": { + "path": "/array-of-one-ofs", + "method": "POST", + "contentTypes": ["application/json"] + }, + "array_request_parameters": { + "path": "/array-request-parameters", + "method": "GET", + "contentTypes": ["application/json"] + }, + "dictionary": { + "path": "/additional-properties", + "method": "POST", + "contentTypes": ["application/json"] + }, + "inline_enum": { + "path": "/inline-enum", + "method": "GET", + "contentTypes": ["application/json"] + }, + "inline_request_body": { + "path": "/inline-request-body", + "method": "POST", + "contentTypes": ["application/json"] + }, + "named_one_of": { + "path": "/named-one-of", + "method": "POST", + "contentTypes": ["application/json"] + }, + "reserved_keywords": { + "path": "/reserved-keywords", + "method": "GET", + "contentTypes": ["application/json"] + }, +} + +class Operations: + @staticmethod + def all(value: T) -> OperationConfig[T]: + """ + Returns an OperationConfig with the same value for every operation + """ + return OperationConfig(**{ operation_id: value for operation_id, _ in OperationLookup.items() }) + +def uri_decode(value): + """ + URI decode a value or list of values + """ + if isinstance(value, list): + return [urllib.parse.unquote(v) for v in value] + return urllib.parse.unquote(value) + +def decode_request_parameters(parameters): + """ + URI decode api request parameters (path, query or multi-value query) + """ + return { key: uri_decode(parameters[key]) if parameters[key] is not None else parameters[key] for key in parameters.keys() } + +def parse_body(body, content_types, model): + """ + Parse the body of an api request into the given model if present + """ + if len([c for c in content_types if c != 'application/json']) == 0: + if model != Any: + body = model.model_validate(json.loads(body)) + else: + body = json.loads(body or '{}') + return body + +def assert_required(required, base_name, parameters): + if required and parameters.get(base_name) is None: + raise Exception(f"Missing required request parameter '{base_name}'") + +def coerce_float(base_name, s): + try: + return float(s) + except Exception as e: + raise Exception(f"Expected a number for request parameter '{base_name}'") + +def coerce_int(base_name, s): + try: + return int(s) + except Exception as e: + raise Exception(f"Expected an integer for request parameter '{base_name}'") + +def coerce_datetime(base_name, s): + try: + return dateutil.parser.parse(s) + except Exception as e: + raise Exception(f"Expected a valid date (iso format) for request parameter '{base_name}'") + +def coerce_bool(base_name, s): + if s == "true": + return True elif s == "false": return False raise Exception(f"Expected a boolean (true or false) for request parameter '{base_name}'") @@ -19277,19 +20373,258 @@ def _build_handler_chain(_interceptors, handler) -> HandlerChain: return RemainingHandlerChain() -class ArrayRequestParametersRequestParameters(BaseModel): +class ArrayOfOneOfsRequestParameters(BaseModel): + """ + Query, path and header parameters for the ArrayOfOneOfs operation + """ + + class Config: + """Pydantic configuration""" + populate_by_name = True + validate_assignment = True + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ArrayOfOneOfsRequestParameters: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + return self.model_dump(exclude={}, exclude_none=True) + + @classmethod + def from_dict(cls, obj: dict) -> ArrayOfOneOfsRequestParameters: + if obj is None: + return None + return ArrayOfOneOfsRequestParameters.model_validate(obj) + + +# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) +ArrayOfOneOfsRequestBody = Any + +ArrayOfOneOfs200OperationResponse = ApiResponse[Literal[200], ArrayOfOneOfs] + +ArrayOfOneOfsOperationResponses = Union[ArrayOfOneOfs200OperationResponse, ] + +# Request type for array_of_one_ofs +ArrayOfOneOfsRequest = ApiRequest[ArrayOfOneOfsRequestParameters, ArrayOfOneOfsRequestBody] +ArrayOfOneOfsChainedRequest = ChainedApiRequest[ArrayOfOneOfsRequestParameters, ArrayOfOneOfsRequestBody] + +class ArrayOfOneOfsHandlerFunction(Protocol): + def __call__(self, input: ArrayOfOneOfsRequest, **kwargs) -> ArrayOfOneOfsOperationResponses: + ... + +ArrayOfOneOfsInterceptor = Callable[[ArrayOfOneOfsChainedRequest], ArrayOfOneOfsOperationResponses] + +def array_of_one_ofs_handler(_handler: ArrayOfOneOfsHandlerFunction = None, interceptors: List[ArrayOfOneOfsInterceptor] = []): + """ + Decorator for an api handler for the array_of_one_ofs operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: ArrayOfOneOfsHandlerFunction): + @wraps(handler) + def wrapper(event, context, additional_interceptors = [], **kwargs): + all_interceptors = additional_interceptors + interceptors + + raw_string_parameters = decode_request_parameters({ + **(event.get('pathParameters', {}) or {}), + **(event.get('queryStringParameters', {}) or {}), + **(event.get('headers', {}) or {}), + }) + raw_string_array_parameters = decode_request_parameters({ + **(event.get('multiValueQueryStringParameters', {}) or {}), + **(event.get('multiValueHeaders', {}) or {}), + }) + + def response_headers_for_status_code(status_code): + headers_for_status = {} + return headers_for_status + + request_parameters = None + try: + request_parameters = ArrayOfOneOfsRequestParameters.from_dict({ + }) + except Exception as e: + return { + 'statusCode': 400, + 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, + 'body': '{"message": "' + str(e) + '"}', + } + + body = {} + interceptor_context = { + "operationId": "array_of_one_ofs", + } + + chain = _build_handler_chain(all_interceptors, handler) + response = chain.next(ApiRequest( + request_parameters, + body, + event, + context, + interceptor_context, + ), **kwargs) + + response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} + response_body = '' + if response.body is None: + pass + elif response.status_code == 200: + response_body = response.body.to_json() + + return { + 'statusCode': response.status_code, + 'headers': response_headers, + 'multiValueHeaders': response.multi_value_headers or {}, + 'body': response_body, + } + return wrapper + + # Support use as a decorator with no arguments, or with interceptor arguments + if callable(_handler): + return _handler_wrapper(_handler) + elif _handler is None: + return _handler_wrapper + else: + raise Exception("Positional arguments are not supported by array_of_one_ofs_handler.") + +class ArrayRequestParametersRequestParameters(BaseModel): + """ + Query, path and header parameters for the ArrayRequestParameters operation + """ + my_string_array_request_params: Optional[List[StrictStr]] + my_enum_array_request_params: Optional[List[MyEnum]] + my_integer_array_request_params: Optional[List[StrictInt]] + my_long_array_request_params: Optional[List[StrictInt]] + my_int32_array_request_params: Optional[List[StrictInt]] + my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] + my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] + my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] + my_enum_request_param: Optional[MyEnum] + + class Config: + """Pydantic configuration""" + populate_by_name = True + validate_assignment = True + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ArrayRequestParametersRequestParameters: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + return self.model_dump(exclude={}, exclude_none=True) + + @classmethod + def from_dict(cls, obj: dict) -> ArrayRequestParametersRequestParameters: + if obj is None: + return None + return ArrayRequestParametersRequestParameters.model_validate(obj) + + +# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) +ArrayRequestParametersRequestBody = Any + +ArrayRequestParameters200OperationResponse = ApiResponse[Literal[200], None] + +ArrayRequestParametersOperationResponses = Union[ArrayRequestParameters200OperationResponse, ] + +# Request type for array_request_parameters +ArrayRequestParametersRequest = ApiRequest[ArrayRequestParametersRequestParameters, ArrayRequestParametersRequestBody] +ArrayRequestParametersChainedRequest = ChainedApiRequest[ArrayRequestParametersRequestParameters, ArrayRequestParametersRequestBody] + +class ArrayRequestParametersHandlerFunction(Protocol): + def __call__(self, input: ArrayRequestParametersRequest, **kwargs) -> ArrayRequestParametersOperationResponses: + ... + +ArrayRequestParametersInterceptor = Callable[[ArrayRequestParametersChainedRequest], ArrayRequestParametersOperationResponses] + +def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunction = None, interceptors: List[ArrayRequestParametersInterceptor] = []): + """ + Decorator for an api handler for the array_request_parameters operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: ArrayRequestParametersHandlerFunction): + @wraps(handler) + def wrapper(event, context, additional_interceptors = [], **kwargs): + all_interceptors = additional_interceptors + interceptors + + raw_string_parameters = decode_request_parameters({ + **(event.get('pathParameters', {}) or {}), + **(event.get('queryStringParameters', {}) or {}), + **(event.get('headers', {}) or {}), + }) + raw_string_array_parameters = decode_request_parameters({ + **(event.get('multiValueQueryStringParameters', {}) or {}), + **(event.get('multiValueHeaders', {}) or {}), + }) + + def response_headers_for_status_code(status_code): + headers_for_status = {} + return headers_for_status + + request_parameters = None + try: + request_parameters = ArrayRequestParametersRequestParameters.from_dict({ + "my_string_array_request_params": coerce_parameter("my-string-array-request-params", "List[str]", raw_string_parameters, raw_string_array_parameters, False), + "my_enum_array_request_params": coerce_parameter("my-enum-array-request-params", "List[MyEnum]", raw_string_parameters, raw_string_array_parameters, False), + "my_integer_array_request_params": coerce_parameter("my-integer-array-request-params", "List[int]", raw_string_parameters, raw_string_array_parameters, False), + "my_long_array_request_params": coerce_parameter("my-long-array-request-params", "List[int]", raw_string_parameters, raw_string_array_parameters, False), + "my_int32_array_request_params": coerce_parameter("my-int32-array-request-params", "List[int]", raw_string_parameters, raw_string_array_parameters, False), + "my_number_array_request_params": coerce_parameter("my-number-array-request-params", "List[float]", raw_string_parameters, raw_string_array_parameters, False), + "my_float_array_request_params": coerce_parameter("my-float-array-request-params", "List[float]", raw_string_parameters, raw_string_array_parameters, False), + "my_double_array_request_params": coerce_parameter("my-double-array-request-params", "List[float]", raw_string_parameters, raw_string_array_parameters, False), + "my_enum_request_param": coerce_parameter("my-enum-request-param", "MyEnum", raw_string_parameters, raw_string_array_parameters, False), + }) + except Exception as e: + return { + 'statusCode': 400, + 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, + 'body': '{"message": "' + str(e) + '"}', + } + + body = {} + interceptor_context = { + "operationId": "array_request_parameters", + } + + chain = _build_handler_chain(all_interceptors, handler) + response = chain.next(ApiRequest( + request_parameters, + body, + event, + context, + interceptor_context, + ), **kwargs) + + response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} + response_body = '' + if response.body is None: + pass + elif response.status_code == 200: + response_body = response.body + + return { + 'statusCode': response.status_code, + 'headers': response_headers, + 'multiValueHeaders': response.multi_value_headers or {}, + 'body': response_body, + } + return wrapper + + # Support use as a decorator with no arguments, or with interceptor arguments + if callable(_handler): + return _handler_wrapper(_handler) + elif _handler is None: + return _handler_wrapper + else: + raise Exception("Positional arguments are not supported by array_request_parameters_handler.") + +class DictionaryRequestParameters(BaseModel): """ - Query, path and header parameters for the ArrayRequestParameters operation + Query, path and header parameters for the Dictionary operation """ - my_string_array_request_params: Optional[List[StrictStr]] - my_enum_array_request_params: Optional[List[MyEnum]] - my_integer_array_request_params: Optional[List[StrictInt]] - my_long_array_request_params: Optional[List[StrictInt]] - my_int32_array_request_params: Optional[List[StrictInt]] - my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] - my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] - my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] - my_enum_request_param: Optional[MyEnum] class Config: """Pydantic configuration""" @@ -19300,41 +20635,41 @@ class ArrayRequestParametersRequestParameters(BaseModel): return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> ArrayRequestParametersRequestParameters: + def from_json(cls, json_str: str) -> DictionaryRequestParameters: return cls.from_dict(json.loads(json_str)) def to_dict(self): return self.model_dump(exclude={}, exclude_none=True) @classmethod - def from_dict(cls, obj: dict) -> ArrayRequestParametersRequestParameters: + def from_dict(cls, obj: dict) -> DictionaryRequestParameters: if obj is None: return None - return ArrayRequestParametersRequestParameters.model_validate(obj) + return DictionaryRequestParameters.model_validate(obj) # Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) -ArrayRequestParametersRequestBody = Any +DictionaryRequestBody = Any -ArrayRequestParameters200OperationResponse = ApiResponse[Literal[200], None] +Dictionary200OperationResponse = ApiResponse[Literal[200], AdditionalPropertiesResponse] -ArrayRequestParametersOperationResponses = Union[ArrayRequestParameters200OperationResponse, ] +DictionaryOperationResponses = Union[Dictionary200OperationResponse, ] -# Request type for array_request_parameters -ArrayRequestParametersRequest = ApiRequest[ArrayRequestParametersRequestParameters, ArrayRequestParametersRequestBody] -ArrayRequestParametersChainedRequest = ChainedApiRequest[ArrayRequestParametersRequestParameters, ArrayRequestParametersRequestBody] +# Request type for dictionary +DictionaryRequest = ApiRequest[DictionaryRequestParameters, DictionaryRequestBody] +DictionaryChainedRequest = ChainedApiRequest[DictionaryRequestParameters, DictionaryRequestBody] -class ArrayRequestParametersHandlerFunction(Protocol): - def __call__(self, input: ArrayRequestParametersRequest, **kwargs) -> ArrayRequestParametersOperationResponses: +class DictionaryHandlerFunction(Protocol): + def __call__(self, input: DictionaryRequest, **kwargs) -> DictionaryOperationResponses: ... -ArrayRequestParametersInterceptor = Callable[[ArrayRequestParametersChainedRequest], ArrayRequestParametersOperationResponses] +DictionaryInterceptor = Callable[[DictionaryChainedRequest], DictionaryOperationResponses] -def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunction = None, interceptors: List[ArrayRequestParametersInterceptor] = []): +def dictionary_handler(_handler: DictionaryHandlerFunction = None, interceptors: List[DictionaryInterceptor] = []): """ - Decorator for an api handler for the array_request_parameters operation, providing a typed interface for inputs and outputs + Decorator for an api handler for the dictionary operation, providing a typed interface for inputs and outputs """ - def _handler_wrapper(handler: ArrayRequestParametersHandlerFunction): + def _handler_wrapper(handler: DictionaryHandlerFunction): @wraps(handler) def wrapper(event, context, additional_interceptors = [], **kwargs): all_interceptors = additional_interceptors + interceptors @@ -19355,16 +20690,7 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc request_parameters = None try: - request_parameters = ArrayRequestParametersRequestParameters.from_dict({ - "my_string_array_request_params": coerce_parameter("my-string-array-request-params", "List[str]", raw_string_parameters, raw_string_array_parameters, False), - "my_enum_array_request_params": coerce_parameter("my-enum-array-request-params", "List[MyEnum]", raw_string_parameters, raw_string_array_parameters, False), - "my_integer_array_request_params": coerce_parameter("my-integer-array-request-params", "List[int]", raw_string_parameters, raw_string_array_parameters, False), - "my_long_array_request_params": coerce_parameter("my-long-array-request-params", "List[int]", raw_string_parameters, raw_string_array_parameters, False), - "my_int32_array_request_params": coerce_parameter("my-int32-array-request-params", "List[int]", raw_string_parameters, raw_string_array_parameters, False), - "my_number_array_request_params": coerce_parameter("my-number-array-request-params", "List[float]", raw_string_parameters, raw_string_array_parameters, False), - "my_float_array_request_params": coerce_parameter("my-float-array-request-params", "List[float]", raw_string_parameters, raw_string_array_parameters, False), - "my_double_array_request_params": coerce_parameter("my-double-array-request-params", "List[float]", raw_string_parameters, raw_string_array_parameters, False), - "my_enum_request_param": coerce_parameter("my-enum-request-param", "MyEnum", raw_string_parameters, raw_string_array_parameters, False), + request_parameters = DictionaryRequestParameters.from_dict({ }) except Exception as e: return { @@ -19375,7 +20701,7 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc body = {} interceptor_context = { - "operationId": "array_request_parameters", + "operationId": "dictionary", } chain = _build_handler_chain(all_interceptors, handler) @@ -19392,7 +20718,7 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc if response.body is None: pass elif response.status_code == 200: - response_body = response.body + response_body = response.body.to_json() return { 'statusCode': response.status_code, @@ -19408,7 +20734,7 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc elif _handler is None: return _handler_wrapper else: - raise Exception("Positional arguments are not supported by array_request_parameters_handler.") + raise Exception("Positional arguments are not supported by dictionary_handler.") class InlineEnumRequestParameters(BaseModel): """ @@ -19567,13 +20893,247 @@ class InlineRequestBodyHandlerFunction(Protocol): def __call__(self, input: InlineRequestBodyRequest, **kwargs) -> InlineRequestBodyOperationResponses: ... -InlineRequestBodyInterceptor = Callable[[InlineRequestBodyChainedRequest], InlineRequestBodyOperationResponses] +InlineRequestBodyInterceptor = Callable[[InlineRequestBodyChainedRequest], InlineRequestBodyOperationResponses] + +def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = None, interceptors: List[InlineRequestBodyInterceptor] = []): + """ + Decorator for an api handler for the inline_request_body operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: InlineRequestBodyHandlerFunction): + @wraps(handler) + def wrapper(event, context, additional_interceptors = [], **kwargs): + all_interceptors = additional_interceptors + interceptors + + raw_string_parameters = decode_request_parameters({ + **(event.get('pathParameters', {}) or {}), + **(event.get('queryStringParameters', {}) or {}), + **(event.get('headers', {}) or {}), + }) + raw_string_array_parameters = decode_request_parameters({ + **(event.get('multiValueQueryStringParameters', {}) or {}), + **(event.get('multiValueHeaders', {}) or {}), + }) + + def response_headers_for_status_code(status_code): + headers_for_status = {} + return headers_for_status + + request_parameters = None + try: + request_parameters = InlineRequestBodyRequestParameters.from_dict({ + }) + except Exception as e: + return { + 'statusCode': 400, + 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, + 'body': '{"message": "' + str(e) + '"}', + } + + # Non-primitive type so parse the body into the appropriate model + body = parse_body(event['body'], ['application/json'], InlineRequestBodyRequestBody) + interceptor_context = { + "operationId": "inline_request_body", + } + + chain = _build_handler_chain(all_interceptors, handler) + response = chain.next(ApiRequest( + request_parameters, + body, + event, + context, + interceptor_context, + ), **kwargs) + + response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} + response_body = '' + if response.body is None: + pass + elif response.status_code == 204: + response_body = response.body + + return { + 'statusCode': response.status_code, + 'headers': response_headers, + 'multiValueHeaders': response.multi_value_headers or {}, + 'body': response_body, + } + return wrapper + + # Support use as a decorator with no arguments, or with interceptor arguments + if callable(_handler): + return _handler_wrapper(_handler) + elif _handler is None: + return _handler_wrapper + else: + raise Exception("Positional arguments are not supported by inline_request_body_handler.") + +class NamedOneOfRequestParameters(BaseModel): + """ + Query, path and header parameters for the NamedOneOf operation + """ + + class Config: + """Pydantic configuration""" + populate_by_name = True + validate_assignment = True + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> NamedOneOfRequestParameters: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + return self.model_dump(exclude={}, exclude_none=True) + + @classmethod + def from_dict(cls, obj: dict) -> NamedOneOfRequestParameters: + if obj is None: + return None + return NamedOneOfRequestParameters.model_validate(obj) + + +# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) +NamedOneOfRequestBody = Any + +NamedOneOf200OperationResponse = ApiResponse[Literal[200], NamedOneOfUnion] + +NamedOneOfOperationResponses = Union[NamedOneOf200OperationResponse, ] + +# Request type for named_one_of +NamedOneOfRequest = ApiRequest[NamedOneOfRequestParameters, NamedOneOfRequestBody] +NamedOneOfChainedRequest = ChainedApiRequest[NamedOneOfRequestParameters, NamedOneOfRequestBody] + +class NamedOneOfHandlerFunction(Protocol): + def __call__(self, input: NamedOneOfRequest, **kwargs) -> NamedOneOfOperationResponses: + ... + +NamedOneOfInterceptor = Callable[[NamedOneOfChainedRequest], NamedOneOfOperationResponses] + +def named_one_of_handler(_handler: NamedOneOfHandlerFunction = None, interceptors: List[NamedOneOfInterceptor] = []): + """ + Decorator for an api handler for the named_one_of operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: NamedOneOfHandlerFunction): + @wraps(handler) + def wrapper(event, context, additional_interceptors = [], **kwargs): + all_interceptors = additional_interceptors + interceptors + + raw_string_parameters = decode_request_parameters({ + **(event.get('pathParameters', {}) or {}), + **(event.get('queryStringParameters', {}) or {}), + **(event.get('headers', {}) or {}), + }) + raw_string_array_parameters = decode_request_parameters({ + **(event.get('multiValueQueryStringParameters', {}) or {}), + **(event.get('multiValueHeaders', {}) or {}), + }) + + def response_headers_for_status_code(status_code): + headers_for_status = {} + return headers_for_status + + request_parameters = None + try: + request_parameters = NamedOneOfRequestParameters.from_dict({ + }) + except Exception as e: + return { + 'statusCode': 400, + 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, + 'body': '{"message": "' + str(e) + '"}', + } + + body = {} + interceptor_context = { + "operationId": "named_one_of", + } + + chain = _build_handler_chain(all_interceptors, handler) + response = chain.next(ApiRequest( + request_parameters, + body, + event, + context, + interceptor_context, + ), **kwargs) + + response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} + response_body = '' + if response.body is None: + pass + elif response.status_code == 200: + response_body = response.body.to_json() + + return { + 'statusCode': response.status_code, + 'headers': response_headers, + 'multiValueHeaders': response.multi_value_headers or {}, + 'body': response_body, + } + return wrapper + + # Support use as a decorator with no arguments, or with interceptor arguments + if callable(_handler): + return _handler_wrapper(_handler) + elif _handler is None: + return _handler_wrapper + else: + raise Exception("Positional arguments are not supported by named_one_of_handler.") + +class ReservedKeywordsRequestParameters(BaseModel): + """ + Query, path and header parameters for the ReservedKeywords operation + """ + var_with: Optional[StrictStr] + var_if: Optional[StrictStr] + var_class: Optional[StrictStr] + + class Config: + """Pydantic configuration""" + populate_by_name = True + validate_assignment = True + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ReservedKeywordsRequestParameters: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + return self.model_dump(exclude={}, exclude_none=True) + + @classmethod + def from_dict(cls, obj: dict) -> ReservedKeywordsRequestParameters: + if obj is None: + return None + return ReservedKeywordsRequestParameters.model_validate(obj) + + +# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) +ReservedKeywordsRequestBody = Any + +ReservedKeywords200OperationResponse = ApiResponse[Literal[200], None] + +ReservedKeywordsOperationResponses = Union[ReservedKeywords200OperationResponse, ] + +# Request type for reserved_keywords +ReservedKeywordsRequest = ApiRequest[ReservedKeywordsRequestParameters, ReservedKeywordsRequestBody] +ReservedKeywordsChainedRequest = ChainedApiRequest[ReservedKeywordsRequestParameters, ReservedKeywordsRequestBody] + +class ReservedKeywordsHandlerFunction(Protocol): + def __call__(self, input: ReservedKeywordsRequest, **kwargs) -> ReservedKeywordsOperationResponses: + ... + +ReservedKeywordsInterceptor = Callable[[ReservedKeywordsChainedRequest], ReservedKeywordsOperationResponses] -def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = None, interceptors: List[InlineRequestBodyInterceptor] = []): +def reserved_keywords_handler(_handler: ReservedKeywordsHandlerFunction = None, interceptors: List[ReservedKeywordsInterceptor] = []): """ - Decorator for an api handler for the inline_request_body operation, providing a typed interface for inputs and outputs + Decorator for an api handler for the reserved_keywords operation, providing a typed interface for inputs and outputs """ - def _handler_wrapper(handler: InlineRequestBodyHandlerFunction): + def _handler_wrapper(handler: ReservedKeywordsHandlerFunction): @wraps(handler) def wrapper(event, context, additional_interceptors = [], **kwargs): all_interceptors = additional_interceptors + interceptors @@ -19594,7 +21154,10 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non request_parameters = None try: - request_parameters = InlineRequestBodyRequestParameters.from_dict({ + request_parameters = ReservedKeywordsRequestParameters.from_dict({ + "var_with": coerce_parameter("with", "str", raw_string_parameters, raw_string_array_parameters, False), + "var_if": coerce_parameter("if", "str", raw_string_parameters, raw_string_array_parameters, False), + "var_class": coerce_parameter("class", "str", raw_string_parameters, raw_string_array_parameters, False), }) except Exception as e: return { @@ -19603,10 +21166,9 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non 'body': '{"message": "' + str(e) + '"}', } - # Non-primitive type so parse the body into the appropriate model - body = parse_body(event['body'], ['application/json'], InlineRequestBodyRequestBody) + body = {} interceptor_context = { - "operationId": "inline_request_body", + "operationId": "reserved_keywords", } chain = _build_handler_chain(all_interceptors, handler) @@ -19622,7 +21184,7 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non response_body = '' if response.body is None: pass - elif response.status_code == 204: + elif response.status_code == 200: response_body = response.body return { @@ -19639,920 +21201,1229 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non elif _handler is None: return _handler_wrapper else: - raise Exception("Positional arguments are not supported by inline_request_body_handler.") + raise Exception("Positional arguments are not supported by reserved_keywords_handler.") + +Interceptor = Callable[[ChainedApiRequest[RequestParameters, RequestBody]], ApiResponse[StatusCode, ResponseBody]] + +def concat_method_and_path(method: str, path: str): + return "{}||{}".format(method.lower(), path) + +OperationIdByMethodAndPath = { concat_method_and_path(method_and_path["method"], method_and_path["path"]): operation for operation, method_and_path in OperationLookup.items() } + +@dataclass +class HandlerRouterHandlers: + array_of_one_ofs: Callable[[Dict, Any], Dict] + array_request_parameters: Callable[[Dict, Any], Dict] + dictionary: Callable[[Dict, Any], Dict] + inline_enum: Callable[[Dict, Any], Dict] + inline_request_body: Callable[[Dict, Any], Dict] + named_one_of: Callable[[Dict, Any], Dict] + reserved_keywords: Callable[[Dict, Any], Dict] + +def handler_router(handlers: HandlerRouterHandlers, interceptors: List[Interceptor] = []): + """ + Returns a lambda handler which can be used to route requests to the appropriate typed lambda handler function. + """ + _handlers = { field.name: getattr(handlers, field.name) for field in fields(handlers) } + + def handler_wrapper(event, context): + operation_id = OperationIdByMethodAndPath[concat_method_and_path(event['requestContext']['httpMethod'], event['requestContext']['resourcePath'])] + handler = _handlers[operation_id] + return handler(event, context, additional_interceptors=interceptors) + return handler_wrapper +", + "test_project/api_client.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + + +import atexit +import datetime +from dateutil.parser import parse +import json +import mimetypes +import os +import re +import tempfile + +from urllib.parse import quote +from typing import Tuple, Optional, List + +from test_project.configuration import Configuration +from test_project.api_response import ApiResponse +import test_project.models +from test_project import rest +from test_project.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :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. + :param cookie: a cookie to include in the header when making calls + to the API + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'object': object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> Tuple: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for \`application/x-www-form-urlencoded\`, \`multipart/form-data\`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for \`multipart/form-data\`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ + + config = self.configuration + + # 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) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + post_params.extend(self.files_parameters(files)) -class ReservedKeywordsRequestParameters(BaseModel): - """ - Query, path and header parameters for the ReservedKeywords operation - """ - var_with: Optional[StrictStr] - var_if: Optional[StrictStr] - var_class: Optional[StrictStr] + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) - class Config: - """Pydantic configuration""" - populate_by_name = True - validate_assignment = True + # body + if body: + body = self.sanitize_for_serialization(body) - def to_json(self) -> str: - return json.dumps(self.to_dict()) + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path - @classmethod - def from_json(cls, json_str: str) -> ReservedKeywordsRequestParameters: - return cls.from_dict(json.loads(json_str)) + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query - def to_dict(self): - return self.model_dump(exclude={}, exclude_none=True) + return method, url, header_params, body, post_params - @classmethod - def from_dict(cls, obj: dict) -> ReservedKeywordsRequestParameters: - if obj is None: - return None - return ReservedKeywordsRequestParameters.model_validate(obj) + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for \`application/x-www-form-urlencoded\`, \`multipart/form-data\`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ -# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) -ReservedKeywordsRequestBody = Any + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) -ReservedKeywords200OperationResponse = ApiResponse[Literal[200], None] + except ApiException as e: + if e.body: + e.body = e.body.decode('utf-8') + raise e -ReservedKeywordsOperationResponses = Union[ReservedKeywords200OperationResponse, ] + return response_data -# Request type for reserved_keywords -ReservedKeywordsRequest = ApiRequest[ReservedKeywordsRequestParameters, ReservedKeywordsRequestBody] -ReservedKeywordsChainedRequest = ChainedApiRequest[ReservedKeywordsRequestParameters, ReservedKeywordsRequestBody] + def response_deserialize( + self, + response_data=None, + response_types_map=None + ) -> ApiResponse: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ -class ReservedKeywordsHandlerFunction(Protocol): - def __call__(self, input: ReservedKeywordsRequest, **kwargs) -> ReservedKeywordsOperationResponses: - ... -ReservedKeywordsInterceptor = Callable[[ReservedKeywordsChainedRequest], ReservedKeywordsOperationResponses] + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) -def reserved_keywords_handler(_handler: ReservedKeywordsHandlerFunction = None, interceptors: List[ReservedKeywordsInterceptor] = []): - """ - Decorator for an api handler for the reserved_keywords operation, providing a typed interface for inputs and outputs - """ - def _handler_wrapper(handler: ReservedKeywordsHandlerFunction): - @wraps(handler) - def wrapper(event, context, additional_interceptors = [], **kwargs): - all_interceptors = additional_interceptors + interceptors + if not 200 <= response_data.status <= 299: + if response_data.status == 400: + raise BadRequestException(http_resp=response_data) - raw_string_parameters = decode_request_parameters({ - **(event.get('pathParameters', {}) or {}), - **(event.get('queryStringParameters', {}) or {}), - **(event.get('headers', {}) or {}), - }) - raw_string_array_parameters = decode_request_parameters({ - **(event.get('multiValueQueryStringParameters', {}) or {}), - **(event.get('multiValueHeaders', {}) or {}), - }) + if response_data.status == 401: + raise UnauthorizedException(http_resp=response_data) - def response_headers_for_status_code(status_code): - headers_for_status = {} - return headers_for_status + if response_data.status == 403: + raise ForbiddenException(http_resp=response_data) - request_parameters = None - try: - request_parameters = ReservedKeywordsRequestParameters.from_dict({ - "var_with": coerce_parameter("with", "str", raw_string_parameters, raw_string_array_parameters, False), - "var_if": coerce_parameter("if", "str", raw_string_parameters, raw_string_array_parameters, False), - "var_class": coerce_parameter("class", "str", raw_string_parameters, raw_string_array_parameters, False), - }) - except Exception as e: - return { - 'statusCode': 400, - 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, - 'body': '{"message": "' + str(e) + '"}', - } + if response_data.status == 404: + raise NotFoundException(http_resp=response_data) - body = {} - interceptor_context = { - "operationId": "reserved_keywords", - } + if 500 <= response_data.status <= 599: + raise ServiceException(http_resp=response_data) + raise ApiException(http_resp=response_data) - chain = _build_handler_chain(all_interceptors, handler) - response = chain.next(ApiRequest( - request_parameters, - body, - event, - context, - interceptor_context, - ), **kwargs) + # deserialize response data - response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} - response_body = '' - if response.body is None: - pass - elif response.status_code == 200: - response_body = response.body + if response_type == "bytearray": + return_data = response_data.data + elif response_type is None: + return_data = None + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + else: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\\-\\d]+)[\\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type) - return { - 'statusCode': response.status_code, - 'headers': response_headers, - 'multiValueHeaders': response.multi_value_headers or {}, - 'body': response_body, - } - return wrapper + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) - # Support use as a decorator with no arguments, or with interceptor arguments - if callable(_handler): - return _handler_wrapper(_handler) - elif _handler is None: - return _handler_wrapper - else: - raise Exception("Positional arguments are not supported by reserved_keywords_handler.") + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. -Interceptor = Callable[[ChainedApiRequest[RequestParameters, RequestBody]], ApiResponse[StatusCode, ResponseBody]] + If obj is None, return None. + 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. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. -def concat_method_and_path(method: str, path: str): - return "{}||{}".format(method.lower(), path) + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + 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 + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() -OperationIdByMethodAndPath = { concat_method_and_path(method_and_path["method"], method_and_path["path"]): operation for operation, method_and_path in OperationLookup.items() } + elif isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes \`openapi_types\`, \`attribute_map\` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = obj.to_dict() + + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } -@dataclass -class HandlerRouterHandlers: - array_request_parameters: Callable[[Dict, Any], Dict] - inline_enum: Callable[[Dict, Any], Dict] - inline_request_body: Callable[[Dict, Any], Dict] - reserved_keywords: Callable[[Dict, Any], Dict] + def deserialize(self, response_text, response_type): + """Deserializes response into an object. -def handler_router(handlers: HandlerRouterHandlers, interceptors: List[Interceptor] = []): - """ - Returns a lambda handler which can be used to route requests to the appropriate typed lambda handler function. - """ - _handlers = { field.name: getattr(handlers, field.name) for field in fields(handlers) } + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. - def handler_wrapper(event, context): - operation_id = OperationIdByMethodAndPath[concat_method_and_path(event['requestContext']['httpMethod'], event['requestContext']['resourcePath'])] - handler = _handlers[operation_id] - return handler(event, context, additional_interceptors=interceptors) - return handler_wrapper -", - "test_project/api_client.py": "# coding: utf-8 + :return: deserialized object. + """ -""" - Edge Cases + # fetch data from response object + try: + data = json.loads(response_text) + except ValueError: + data = response_text - No description provided + return self.__deserialize(data, response_type) - The version of the OpenAPI document: 1.0.0 + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. - NOTE: This class is auto generated. - Do not edit the class manually. -""" # noqa: E501 + :param data: dict, list or str. + :param klass: class literal, or string of class name. + :return: object. + """ + if data is None: + return None -import atexit -import datetime -from dateutil.parser import parse -import json -import mimetypes -import os -import re -import tempfile + if isinstance(klass, str): + if klass.startswith('List['): + sub_kls = re.match(r'List\\[(.*)]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] -from urllib.parse import quote -from typing import Tuple, Optional, List + if klass.startswith('Dict['): + sub_kls = re.match(r'Dict\\[([^,]*), (.*)]', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} -from test_project.configuration import Configuration -from test_project.api_response import ApiResponse -import test_project.models -from test_project import rest -from test_project.exceptions import ( - ApiValueError, - ApiException, - BadRequestException, - UnauthorizedException, - ForbiddenException, - NotFoundException, - ServiceException -) + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(test_project.models, klass) + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + else: + return self.__deserialize_model(data, klass) -class ApiClient: - """Generic API client for OpenAPI client library builds. + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. + :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 params.items() 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 - :param configuration: .Configuration object for this client - :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. - :param cookie: a cookie to include in the header when making calls - to the API - """ + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. - PRIMITIVE_TYPES = (float, bool, bytes, str, int) - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int, # TODO remove as only py3 is supported? - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, - } - _pool = None + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) - def __init__( - self, - configuration=None, - header_name=None, - header_value=None, - cookie=None - ) -> None: - # use default configuration if none is provided - if configuration is None: - configuration = Configuration.get_default() - self.configuration = configuration + 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(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'OpenAPI-Generator/1.0.0/python' - self.client_side_validation = configuration.client_side_validation + return "&".join(["=".join(item) for item in new_params]) - def __enter__(self): - return self + def files_parameters(self, files=None): + """Builds form parameters. - def __exit__(self, exc_type, exc_value, traceback): - pass + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] + if files: + for k, v in files.items(): + if not v: + continue + file_names = v if type(v) is list else [v] + for n in file_names: + with open(n, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value + return params - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value + def select_header_accept(self, accepts: List[str]) -> Optional[str]: + """Returns \`Accept\` based on an array of accepts provided. + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return None - _default = None + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept - @classmethod - def get_default(cls): - """Return new instance of ApiClient. + return accepts[0] - This method returns newly created, based on default constructor, - object of ApiClient class or returns a copy of default - ApiClient. + def select_header_content_type(self, content_types): + """Returns \`Content-Type\` based on an array of content_types provided. - :return: The ApiClient object. + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). """ - if cls._default is None: - cls._default = ApiClient() - return cls._default + if not content_types: + return None - @classmethod - def set_default(cls, default): - """Set default instance of ApiClient. + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type - It stores default ApiClient. + return content_types[0] - :param default: object of ApiClient. + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. """ - cls._default = default + if not auth_settings: + return - def param_serialize( + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( self, - method, + headers, + queries, resource_path, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, auth_settings=None, - collection_formats=None, - _host=None, - _request_auth=None - ) -> Tuple: + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting - """Builds the HTTP request params needed by the request. - :param method: Method to call. - :param resource_path: Path to method endpoint. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for \`application/x-www-form-urlencoded\`, \`multipart/form-data\`. - :param auth_settings list: Auth Settings names for the request. - :param files dict: key -> filename, value -> filepath, - for \`multipart/form-data\`. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :return: tuple of form (path, http_method, query_params, header_params, - body, post_params, files) + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in \`query\` or \`header\`' + ) - config = self.configuration + def __deserialize_file(self, response): + """Deserializes body to file - # 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) - ) + Saves response body into a file in a temporary folder, + using the filename from the \`Content-Disposition\` header if provided. - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples( - path_params, - collection_formats - ) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) + handle file downloading + save response body into a tmp file and return the instance - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples( - post_params, - collection_formats - ) - post_params.extend(self.files_parameters(files)) + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) - # auth setting - self.update_params_for_auth( - header_params, - query_params, - auth_settings, - resource_path, - method, - body, - request_auth=_request_auth - ) + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.search( + r'filename=[\\'"]?([^\\'"\\s]+)[\\'"]?', + content_disposition + ).group(1) + path = os.path.join(os.path.dirname(path), filename) - # body - if body: - body = self.sanitize_for_serialization(body) + with open(path, "wb") as f: + f.write(response.data) - # request url - if _host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = _host + resource_path + return path - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query( - query_params, - collection_formats - ) - url += "?" + url_query + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. - return method, url, header_params, body, post_params + :param data: str. + :param klass: class literal. + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data - def call_api( - self, - method, - url, - header_params=None, - body=None, - post_params=None, - _request_timeout=None - ) -> rest.RESTResponse: - """Makes the HTTP request (synchronous) - :param method: Method to call. - :param url: Path to method endpoint. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for \`application/x-www-form-urlencoded\`, \`multipart/form-data\`. - :param _request_timeout: timeout setting for this request. - :return: RESTResponse + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse \`{0}\` as date object".format(string) + ) + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ try: - # perform request and return response - response_data = self.rest_client.request( - method, url, - headers=header_params, - body=body, post_params=post_params, - _request_timeout=_request_timeout + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse \`{0}\` as datetime object" + .format(string) + ) ) - except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') - raise e - - return response_data + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. - def response_deserialize( - self, - response_data=None, - response_types_map=None - ) -> ApiResponse: - """Deserializes response into an object. - :param response_data: RESTResponse object to be deserialized. - :param response_types_map: dict of response types. - :return: ApiResponse + :param data: dict, list. + :param klass: class literal. + :return: model object. """ + return klass.from_dict(data) +", + "test_project/api_response.py": """"API response object.""" - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) +from __future__ import annotations +from typing import Any, Dict, Optional, Generic, TypeVar +from pydantic import Field, StrictInt, StrictStr, StrictBytes, BaseModel - if not 200 <= response_data.status <= 299: - if response_data.status == 400: - raise BadRequestException(http_resp=response_data) +T = TypeVar("T") - if response_data.status == 401: - raise UnauthorizedException(http_resp=response_data) +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ - if response_data.status == 403: - raise ForbiddenException(http_resp=response_data) + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - if response_data.status == 404: - raise NotFoundException(http_resp=response_data) + model_config = { + "arbitrary_types_allowed": True + } +", + "test_project/configuration.py": "# coding: utf-8 - if 500 <= response_data.status <= 599: - raise ServiceException(http_resp=response_data) - raise ApiException(http_resp=response_data) +""" + Edge Cases - # deserialize response data + No description provided - if response_type == "bytearray": - return_data = response_data.data - elif response_type is None: - return_data = None - elif response_type == "file": - return_data = self.__deserialize_file(response_data) - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\\-\\d]+)[\\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_text = response_data.data.decode(encoding) - return_data = self.deserialize(response_text, response_type) + The version of the OpenAPI document: 1.0.0 - return ApiResponse( - status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data - ) + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - If obj is None, return None. - 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. - If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. +import copy +import logging +import sys +import urllib3 - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - 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 - ) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() +import http.client as httplib - elif isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes \`openapi_types\`, \`attribute_map\` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = obj.to_dict() +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} - return { - key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items() - } +class Configuration: + """This class contains various settings of the API client. - def deserialize(self, response_text, response_type): - """Deserializes response into an object. + :param host: Base url. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum + values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. + """ - :return: deserialized object. + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + access_token=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ssl_ca_cert=None, + ) -> None: + """Constructor + """ + self._base_path = "http://localhost" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("test_project") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch """ - # fetch data from response object - try: - data = json.loads(response_text) - except ValueError: - data = response_text - - return self.__deserialize(data, response_type) - - def __deserialize(self, 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. + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. """ - if data is None: - return None - - if isinstance(klass, str): - if klass.startswith('List['): - sub_kls = re.match(r'List\\[(.*)]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] - - if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\\[([^,]*), (.*)]', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in data.items()} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(test_project.models, klass) - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datetime(data) - else: - return self.__deserialize_model(data, klass) - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. + self.proxy = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True - :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 + self.socket_options = None + """Options to pass down to the underlying urllib3 socket """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() 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 parameters_to_url_query(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: URL query string (e.g. a=Hello%20World&b=123) + self.date_format = "%Y-%m-%d" + """date format """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: - if isinstance(v, bool): - v = str(v).lower() - if isinstance(v, (int, float)): - v = str(v) - if isinstance(v, dict): - v = json.dumps(v) - 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(quote(str(value)) for value in v)) - ) - else: - new_params.append((k, quote(str(v)))) + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result - return "&".join(["=".join(item) for item in new_params]) + def __setattr__(self, name, value): + object.__setattr__(self, name, value) - def files_parameters(self, files=None): - """Builds form parameters. + @classmethod + def set_default(cls, default): + """Set default instance of configuration. - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] + It stores default configuration, which can be + returned by get_default_copy method. - if files: - for k, v in files.items(): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = ( - mimetypes.guess_type(filename)[0] - or 'application/octet-stream' - ) - params.append( - tuple([k, tuple([filename, filedata, mimetype])]) - ) + :param default: object of Configuration + """ + cls._default = default - return params + @classmethod + def get_default_copy(cls): + """Deprecated. Please use \`get_default\` instead. - def select_header_accept(self, accepts: List[str]) -> Optional[str]: - """Returns \`Accept\` based on an array of accepts provided. + Deprecated. Please use \`get_default\` instead. - :param accepts: List of headers. - :return: Accept (e.g. application/json). + :return: The configuration object. """ - if not accepts: - return None - - for accept in accepts: - if re.search('json', accept, re.IGNORECASE): - return accept + return cls.get_default() - return accepts[0] + @classmethod + def get_default(cls): + """Return the default configuration. - def select_header_content_type(self, content_types): - """Returns \`Content-Type\` based on an array of content_types provided. + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). + :return: The configuration object. """ - if not content_types: - return None - - for content_type in content_types: - if re.search('json', content_type, re.IGNORECASE): - return content_type - - return content_types[0] + if cls._default is None: + cls._default = Configuration() + return cls._default - def update_params_for_auth( - self, - headers, - queries, - auth_settings, - resource_path, - method, - body, - request_auth=None - ) -> None: - """Updates header and query params based on authentication setting. + @property + def logger_file(self): + """The logger file. - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param request_auth: if set, the provided settings will - override the token in the configuration. + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str """ - if not auth_settings: - return + return self.__logger_file - if request_auth: - self._apply_auth_params( - headers, - queries, - resource_path, - method, - body, - request_auth - ) - else: - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params( - headers, - queries, - resource_path, - method, - body, - auth_setting - ) + @logger_file.setter + def logger_file(self, value): + """The logger file. - def _apply_auth_params( - self, - headers, - queries, - resource_path, - method, - body, - auth_setting - ) -> None: - """Updates the request parameters based on a single auth_setting + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param auth_setting: auth settings for the endpoint + :param value: The logger_file path. + :type: str """ - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError( - 'Authentication token must be in \`query\` or \`header\`' - ) + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) - def __deserialize_file(self, response): - """Deserializes body to file + @property + def debug(self): + """Debug status - Saves response body into a file in a temporary folder, - using the filename from the \`Content-Disposition\` header if provided. + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug - handle file downloading - save response body into a tmp file and return the instance + @debug.setter + def debug(self, value): + """Debug status - :param response: RESTResponse. - :return: file path. + :param value: The debug status, True or False. + :type: bool """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default \`logging.WARNING\` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search( - r'filename=[\\'"]?([^\\'"\\s]+)[\\'"]?', - content_disposition - ).group(1) - path = os.path.join(os.path.dirname(path), filename) + @property + def logger_format(self): + """The logger format. - with open(path, "wb") as f: - f.write(response.data) + The logger_formatter will be updated when sets logger_format. - return path + :param value: The format string. + :type: str + """ + return self.__logger_format - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. + @logger_format.setter + def logger_format(self, value): + """The logger format. - :param data: str. - :param klass: class literal. + The logger_formatter will be updated when sets logger_format. - :return: int, long, float, str, bool. + :param value: The format string. + :type: str """ - try: - return klass(data) - except UnicodeEncodeError: - return str(data) - except TypeError: - return data + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) - def __deserialize_object(self, value): - """Return an original value. + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). - :return: object. + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. """ - return value + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key - def __deserialize_date(self, string): - """Deserializes string to date. + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). - :param string: str. - :return: date. + :return: The token for basic HTTP authentication. """ - try: - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse \`{0}\` as date object".format(string) - ) + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') - def __deserialize_datetime(self, string): - """Deserializes string to datetime. + def auth_settings(self): + """Gets Auth Settings dict for api client. - The string should be in iso8601 datetime format. + :return: The Auth Settings information dict. + """ + auth = {} + return auth - :param string: str. - :return: datetime. + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. """ - try: - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=( - "Failed to parse \`{0}\` as datetime object" - .format(string) - ) - ) + return "Python SDK Debug Report:\\n"\\ + "OS: {env}\\n"\\ + "Python Version: {pyversion}\\n"\\ + "Version of the API: 1.0.0\\n"\\ + "SDK Package Version: 1.0.0".\\ + format(env=sys.platform, pyversion=sys.version) - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. + def get_host_settings(self): + """Gets an array of host settings - :param data: dict, list. - :param klass: class literal. - :return: model object. + :return: An array of host settings + """ + return [ + { + 'url': "", + 'description': "No description provided", + } + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] - return klass.from_dict(data) -", - "test_project/api_response.py": """"API response object.""" + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) -from __future__ import annotations -from typing import Any, Dict, Optional, Generic, TypeVar -from pydantic import Field, StrictInt, StrictStr, StrictBytes, BaseModel + if 'enum_values' in variable \\ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable \`{0}\` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) -T = TypeVar("T") + url = url.replace("{" + variable_name + "}", used_value) -class ApiResponse(BaseModel, Generic[T]): - """ - API response object - """ + return url - status_code: StrictInt = Field(description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: T = Field(description="Deserialized data given the data type") - raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) - model_config = { - "arbitrary_types_allowed": True - } + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None ", - "test_project/configuration.py": "# coding: utf-8 + "test_project/exceptions.py": "# coding: utf-8 """ Edge Cases @@ -20565,421 +22436,465 @@ class ApiResponse(BaseModel, Generic[T]): Do not edit the class manually. """ # noqa: E501 +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" -import copy -import logging -import sys -import urllib3 - -import http.client as httplib - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' -} -class Configuration: - """This class contains various settings of the API client. +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors - :param host: Base url. - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer). - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication. - :param password: Password for HTTP basic authentication. - :param access_token: Access token. - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum - values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format. + Args: + msg (str): the exception message - """ + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) - _default = None - def __init__(self, host=None, - api_key=None, api_key_prefix=None, - username=None, password=None, - access_token=None, - server_index=None, server_variables=None, - server_operation_index=None, server_operation_variables=None, - ssl_ca_cert=None, - ) -> None: - """Constructor - """ - self._base_path = "http://localhost" if host is None else host - """Default Base url - """ - self.server_index = 0 if server_index is None and host is None else server_index - self.server_operation_index = server_operation_index or {} - """Default server index - """ - self.server_variables = server_variables or {} - self.server_operation_variables = server_operation_variables or {} - """Default server variables - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - self.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.access_token = access_token - """Access token - """ - self.logger = {} - """Logging Settings +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: """ - self.logger["package_logger"] = logging.getLogger("test_project") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - """Log format + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset """ - self.logger_stream_handler = None - """Log stream handler + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: """ - self.logger_file_handler = None - """Log file handler + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict """ - self.logger_file = None - """Debug file location + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: """ - self.debug = False - """Debug switch + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data.decode('utf-8') + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\\n"\\ + "Reason: {1}\\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\\n".format(self.body) + + return error_message + +class BadRequestException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(BadRequestException, self).__init__(status, reason, http_resp) + +class NotFoundException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(ApiException): - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = ssl_ca_cert - """Set this to customize the certificate file to verify the peer. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - self.tls_server_name = None - """SSL/TLS Server Name Indication (SNI) - Set this to the SNI value expected by the server. - """ + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(UnauthorizedException, self).__init__(status, reason, http_resp) - self.proxy = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = '' - """Safe chars for path_param - """ - self.retries = None - """Adding retries to override urllib3 default value 3 - """ - # Enable client side validation - self.client_side_validation = True +class ForbiddenException(ApiException): - self.socket_options = None - """Options to pass down to the underlying urllib3 socket - """ + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(ForbiddenException, self).__init__(status, reason, http_resp) - self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" - """datetime format - """ - self.date_format = "%Y-%m-%d" - """date format - """ +class ServiceException(ApiException): - def __deepcopy__(self, memo): - cls = self.__class__ - result = cls.__new__(cls) - memo[id(self)] = result - for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler'): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(ServiceException, self).__init__(status, reason, http_resp) - def __setattr__(self, name, value): - object.__setattr__(self, name, value) - @classmethod - def set_default(cls, default): - """Set default instance of configuration. +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result +", + "test_project/interceptors/__init__.py": "from test_project.interceptors.response_headers import cors_interceptor +from test_project.interceptors.try_catch import try_catch_interceptor +from test_project.interceptors.powertools.logger import LoggingInterceptor +from test_project.interceptors.powertools.tracer import TracingInterceptor +from test_project.interceptors.powertools.metrics import MetricsInterceptor - It stores default configuration, which can be - returned by get_default_copy method. +# All default interceptors, for logging, tracing, metrics, cors headers and error handling +INTERCEPTORS = [ + cors_interceptor, + LoggingInterceptor().intercept, + try_catch_interceptor, + TracingInterceptor().intercept, + MetricsInterceptor().intercept, +] +", + "test_project/interceptors/powertools/logger.py": "from aws_lambda_powertools import Logger +from aws_lambda_powertools.logging.logger import _is_cold_start +from test_project.api.operation_config import ApiResponse, ChainedApiRequest - :param default: object of Configuration +logger = Logger() + +class LoggingInterceptor: + + def intercept(self, request: ChainedApiRequest) -> ApiResponse: """ - cls._default = default + An interceptor for adding an aws powertools logger to the interceptor context + See: https://docs.powertools.aws.dev/lambda/python/latest/core/logger/ + """ + request.interceptor_context["logger"] = logger - @classmethod - def get_default_copy(cls): - """Deprecated. Please use \`get_default\` instead. + # Add the operation id, lambda context and cold start + logger.append_keys( + operationId=request.interceptor_context["operationId"], + **request.context.__dict__, + cold_start=_is_cold_start() + ) + response = request.chain.next(request) + logger.remove_keys(["operationId"]) - Deprecated. Please use \`get_default\` instead. + return response - :return: The configuration object. + @staticmethod + def get_logger(request: ChainedApiRequest) -> Logger: + if request.interceptor_context.get("logger") is None: + raise Exception("No logger found. Did you configure the LoggingInterceptor?") + return request.interceptor_context["logger"] +", + "test_project/interceptors/powertools/metrics.py": "from aws_lambda_powertools import Metrics +from test_project.api.operation_config import ApiResponse, ChainedApiRequest + +metrics = Metrics() + +class MetricsInterceptor: + + def intercept(self, request: ChainedApiRequest) -> ApiResponse: """ - return cls.get_default() + An interceptor for adding an aws powertools metrics instance to the interceptor context + See: https://docs.powertools.aws.dev/lambda/python/latest/core/metrics/ + """ + operation_id = request.interceptor_context["operationId"] - @classmethod - def get_default(cls): - """Return the default configuration. + # Set the namespace if not set via environment variables + if metrics.namespace is None: + metrics.namespace = operation_id - This method returns newly created, based on default constructor, - object of Configuration class or returns a copy of default - configuration. + request.interceptor_context["metrics"] = metrics - :return: The configuration object. + try: + metrics.add_dimension(name="operationId", value=operation_id) + return request.chain.next(request) + finally: + metrics.flush_metrics() + + @staticmethod + def get_metrics(request: ChainedApiRequest) -> Metrics: """ - if cls._default is None: - cls._default = Configuration() - return cls._default + Retrieve the metrics logger from the request + """ + if request.interceptor_context.get("metrics") is None: + raise Exception("No metrics found. Did you configure the MetricsInterceptor?") + return request.interceptor_context["metrics"] +", + "test_project/interceptors/powertools/tracer.py": "from aws_lambda_powertools import Tracer +from test_project.api.operation_config import ApiResponse, ChainedApiRequest - @property - def logger_file(self): - """The logger file. +tracer = Tracer() +is_cold_start = True - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. +class TracingInterceptor: + def __init__(self, add_response_as_metadata: bool = False): + self._add_response_as_metadata = add_response_as_metadata - :param value: The logger_file path. - :type: str + def intercept(self, request: ChainedApiRequest) -> ApiResponse: """ - return self.__logger_file + An interceptor for adding an aws powertools tracer to the interceptor context + See: https://docs.powertools.aws.dev/lambda/python/latest/core/tracer/ + """ + request.interceptor_context["tracer"] = tracer - @logger_file.setter - def logger_file(self, value): - """The logger file. + operation_id = request.interceptor_context["operationId"] - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. + with tracer.provider.in_subsegment(name=f"## {operation_id}") as subsegment: + try: + result = request.chain.next(request) + tracer._add_response_as_metadata( + method_name=operation_id, + data=result, + subsegment=subsegment, + capture_response=self._add_response_as_metadata + ) + return result + except Exception as e: + tracer._add_full_exception_as_metadata( + method_name=operation_id, + error=e, + subsegment=subsegment, + capture_error=True + ) + raise + finally: + global is_cold_start + subsegment.put_annotation(key="ColdStart", value=is_cold_start) + is_cold_start = False - :param value: The logger_file path. - :type: str + @staticmethod + def get_tracer(request: ChainedApiRequest) -> Tracer: """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_file_handler) + Retrieve the metrics logger from the request + """ + if request.interceptor_context.get("tracer") is None: + raise Exception("No tracer found. Did you configure the TracingInterceptor?") + return request.interceptor_context["tracer"] +", + "test_project/interceptors/response_headers.py": "from test_project.api.operation_config import ApiResponse, ChainedApiRequest +from typing import Dict + +CORS_HEADERS = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Headers": "*", +} + +def build_response_headers_interceptor(headers: Dict[str, str]): + """ + Build an interceptor for adding headers to the response. + """ + def response_headers_interceptor(request: ChainedApiRequest) -> ApiResponse: + result = request.chain.next(request) + result.headers = { **headers, **(result.headers or {}) } + return result + + # Any error responses returned during request validation will include the headers + response_headers_interceptor.__type_safe_api_response_headers = headers - @property - def debug(self): - """Debug status + return response_headers_interceptor - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug +# Cors interceptor allows all origins and headers. Use build_response_headers_interceptors to customise +cors_interceptor = build_response_headers_interceptor(CORS_HEADERS) - @debug.setter - def debug(self, value): - """Debug status +", + "test_project/interceptors/try_catch.py": "from test_project.api.operation_config import ApiResponse, ChainedApiRequest +from test_project.response import Response - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in self.logger.items(): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default \`logging.WARNING\` - for _, logger in self.logger.items(): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - @property - def logger_format(self): - """The logger format. +def try_catch_interceptor(request: ChainedApiRequest) -> ApiResponse: + """ + Interceptor for catching unhandled exceptions and returning a 500 error. + Uncaught exceptions which are ApiResponses will be returned, such that deeply nested code may return error + responses, eg: \`throw Response.not_found(...)\` + """ + try: + return request.chain.next(request) + except ApiResponse as response: + # If the error is a response, return it as the response + return response + except Exception as e: + if request.interceptor_context.get("logger") is not None: + request.interceptor_context.get("logger").exception("Interceptor caught exception") + else: + print("Interceptor caught exception") + print(e) - The logger_formatter will be updated when sets logger_format. + return Response.internal_failure({ "message": "Internal Error" }) +", + "test_project/models/__init__.py": "# coding: utf-8 - :param value: The format string. - :type: str - """ - return self.__logger_format +# flake8: noqa +""" + Edge Cases - @logger_format.setter - def logger_format(self, value): - """The logger format. + No description provided - The logger_formatter will be updated when sets logger_format. + The version of the OpenAPI document: 1.0.0 - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 - def get_api_key_with_prefix(self, identifier, alias=None): - """Gets API key (with prefix if set). +# import models into model package +from test_project.models.additional_properties_response import AdditionalPropertiesResponse +from test_project.models.another_named_one_of import AnotherNamedOneOf +from test_project.models.array_of_one_ofs import ArrayOfOneOfs +from test_project.models.dictionary import Dictionary +from test_project.models.inline_enum200_response import InlineEnum200Response +from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum +from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent +from test_project.models.my_enum import MyEnum +from test_project.models.named_one_of import NamedOneOf +from test_project.models.named_one_of_union import NamedOneOfUnion +from test_project.models.some_object import SomeObject +", + "test_project/models/additional_properties_response.py": "# coding: utf-8 - :param identifier: The identifier of apiKey. - :param alias: The alternative identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key +""" + Edge Cases - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). + No description provided - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') + The version of the OpenAPI document: 1.0.0 - def auth_settings(self): - """Gets Auth Settings dict for api client. + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 - :return: The Auth Settings information dict. - """ - auth = {} - return auth +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +from test_project.models.dictionary import Dictionary +try: + from typing import Self +except ImportError: + from typing_extensions import Self - def to_debug_report(self): - """Gets the essential information for debugging. +class AdditionalPropertiesResponse(BaseModel): + """ + AdditionalPropertiesResponse + """ # noqa: E501 + dictionary_of_objects: Optional[Dictionary] = Field(default=None, alias="dictionaryOfObjects") + dictionary_of_primitives: Optional[Dict[str, StrictStr]] = Field(default=None, alias="dictionaryOfPrimitives") + __properties: ClassVar[List[str]] = ["dictionaryOfObjects", "dictionaryOfPrimitives"] - :return: The report for debugging. - """ - return "Python SDK Debug Report:\\n"\\ - "OS: {env}\\n"\\ - "Python Version: {pyversion}\\n"\\ - "Version of the API: 1.0.0\\n"\\ - "SDK Package Version: 1.0.0".\\ - format(env=sys.platform, pyversion=sys.version) - def get_host_settings(self): - """Gets an array of host settings + model_config = { + "populate_by_name": True, + "validate_assignment": True + } - :return: An array of host settings - """ - return [ - { - 'url': "", - 'description': "No description provided", - } - ] + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - def get_host_from_settings(self, index, variables=None, servers=None): - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :param servers: an array of host settings or None - :return: URL based on host settings - """ - if index is None: - return self._base_path + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - variables = {} if variables is None else variables - servers = self.get_host_settings() if servers is None else servers + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AdditionalPropertiesResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - url = server['url'] + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: - # go through variables and replace placeholders - for variable_name, variable in server.get('variables', {}).items(): - used_value = variables.get( - variable_name, variable['default_value']) + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling \`to_dict()\` of dictionary_of_objects + if self.dictionary_of_objects: + _dict['dictionaryOfObjects'] = self.dictionary_of_objects.to_dict() + return _dict - if 'enum_values' in variable \\ - and used_value not in variable['enum_values']: - raise ValueError( - "The variable \`{0}\` in the host URL has invalid value " - "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of AdditionalPropertiesResponse from a dict""" - url = url.replace("{" + variable_name + "}", used_value) + if obj is None: + return None - return url + if not isinstance(obj, dict): + return cls.model_validate(obj) - @property - def host(self): - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) + _obj = cls.model_validate({ + "dictionaryOfObjects": Dictionary.from_dict(obj.get("dictionaryOfObjects")) if obj.get("dictionaryOfObjects") is not None else None, + "dictionaryOfPrimitives": obj.get("dictionaryOfPrimitives") + }) + return _obj - @host.setter - def host(self, value): - """Fix base path.""" - self._base_path = value - self.server_index = None ", - "test_project/exceptions.py": "# coding: utf-8 + "test_project/models/another_named_one_of.py": "# coding: utf-8 """ Edge Cases @@ -20992,345 +22907,370 @@ class Configuration: Do not edit the class manually. """ # noqa: E501 -class OpenApiException(Exception): - """The base exception class for all OpenAPIExceptions""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AnotherNamedOneOf(BaseModel): + """ + AnotherNamedOneOf + """ # noqa: E501 + bar: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["bar"] -class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, - key_type=None) -> None: - """ Raises an exception for TypeErrors + model_config = { + "populate_by_name": True, + "validate_assignment": True + } - Args: - msg (str): the exception message + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - Keyword Args: - path_to_item (list): a list of keys an indices to get to the - current_item - None if unset - valid_classes (tuple): the primitive classes that current item - should be an instance of - None if unset - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - None if unset - """ - self.path_to_item = path_to_item - self.valid_classes = valid_classes - self.key_type = key_type - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiTypeError, self).__init__(full_msg) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AnotherNamedOneOf from a JSON string""" + return cls.from_dict(json.loads(json_str)) -class ApiValueError(OpenApiException, ValueError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Args: - msg (str): the exception message + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - Keyword Args: - path_to_item (list) the path to the exception in the - received_data dict. None if unset - """ + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiValueError, self).__init__(full_msg) + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of AnotherNamedOneOf from a dict""" -class ApiAttributeError(OpenApiException, AttributeError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Raised when an attribute reference or assignment fails. + if obj is None: + return None - Args: - msg (str): the exception message + if not isinstance(obj, dict): + return cls.model_validate(obj) - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiAttributeError, self).__init__(full_msg) + _obj = cls.model_validate({ + "bar": obj.get("bar") + }) + return _obj +", + "test_project/models/array_of_one_ofs.py": "# coding: utf-8 -class ApiKeyError(OpenApiException, KeyError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Args: - msg (str): the exception message +""" + Edge Cases - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiKeyError, self).__init__(full_msg) + No description provided + The version of the OpenAPI document: 1.0.0 -class ApiException(OpenApiException): + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 - def __init__(self, status=None, reason=None, http_resp=None) -> None: - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data.decode('utf-8') - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +from test_project.models.named_one_of_union import NamedOneOfUnion +try: + from typing import Self +except ImportError: + from typing_extensions import Self - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\\n"\\ - "Reason: {1}\\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\\n".format( - self.headers) +class ArrayOfOneOfs(BaseModel): + """ + ArrayOfOneOfs + """ # noqa: E501 + one_ofs: Optional[List[Any]] = Field(default=None, alias="oneOfs") + __properties: ClassVar[List[str]] = ["oneOfs"] - if self.body: - error_message += "HTTP response body: {0}\\n".format(self.body) - return error_message + model_config = { + "populate_by_name": True, + "validate_assignment": True + } -class BadRequestException(ApiException): + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(BadRequestException, self).__init__(status, reason, http_resp) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) -class NotFoundException(ApiException): + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ArrayOfOneOfs from a JSON string""" + return cls.from_dict(json.loads(json_str)) - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(NotFoundException, self).__init__(status, reason, http_resp) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: -class UnauthorizedException(ApiException): + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling \`to_dict()\` of one_ofs + if self.one_ofs: + _dict['oneOfs'] = self.one_ofs.to_dict() + return _dict - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(UnauthorizedException, self).__init__(status, reason, http_resp) + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ArrayOfOneOfs from a dict""" + if obj is None: + return None -class ForbiddenException(ApiException): + if not isinstance(obj, dict): + return cls.model_validate(obj) - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ForbiddenException, self).__init__(status, reason, http_resp) + _obj = cls.model_validate({ + "oneOfs": List[NamedOneOfUnion].from_dict(obj.get("oneOfs")) if obj.get("oneOfs") is not None else None + }) + return _obj +", + "test_project/models/dictionary.py": "# coding: utf-8 -class ServiceException(ApiException): +""" + Edge Cases - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ServiceException, self).__init__(status, reason, http_resp) + No description provided + The version of the OpenAPI document: 1.0.0 -def render_path(path_to_item): - """Returns a string representation of a path""" - result = "" - for pth in path_to_item: - if isinstance(pth, int): - result += "[{0}]".format(pth) - else: - result += "['{0}']".format(pth) - return result -", - "test_project/interceptors/__init__.py": "from test_project.interceptors.response_headers import cors_interceptor -from test_project.interceptors.try_catch import try_catch_interceptor -from test_project.interceptors.powertools.logger import LoggingInterceptor -from test_project.interceptors.powertools.tracer import TracingInterceptor -from test_project.interceptors.powertools.metrics import MetricsInterceptor + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 -# All default interceptors, for logging, tracing, metrics, cors headers and error handling -INTERCEPTORS = [ - cors_interceptor, - LoggingInterceptor().intercept, - try_catch_interceptor, - TracingInterceptor().intercept, - MetricsInterceptor().intercept, -] -", - "test_project/interceptors/powertools/logger.py": "from aws_lambda_powertools import Logger -from aws_lambda_powertools.logging.logger import _is_cold_start -from test_project.api.operation_config import ApiResponse, ChainedApiRequest +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self -logger = Logger() +class Dictionary(BaseModel): + """ + Dictionary + """ # noqa: E501 + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = [] -class LoggingInterceptor: - def intercept(self, request: ChainedApiRequest) -> ApiResponse: - """ - An interceptor for adding an aws powertools logger to the interceptor context - See: https://docs.powertools.aws.dev/lambda/python/latest/core/logger/ - """ - request.interceptor_context["logger"] = logger + model_config = { + "populate_by_name": True, + "validate_assignment": True + } - # Add the operation id, lambda context and cold start - logger.append_keys( - operationId=request.interceptor_context["operationId"], - **request.context.__dict__, - cold_start=_is_cold_start() - ) - response = request.chain.next(request) - logger.remove_keys(["operationId"]) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - return response + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - @staticmethod - def get_logger(request: ChainedApiRequest) -> Logger: - if request.interceptor_context.get("logger") is None: - raise Exception("No logger found. Did you configure the LoggingInterceptor?") - return request.interceptor_context["logger"] -", - "test_project/interceptors/powertools/metrics.py": "from aws_lambda_powertools import Metrics -from test_project.api.operation_config import ApiResponse, ChainedApiRequest + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Dictionary from a JSON string""" + return cls.from_dict(json.loads(json_str)) -metrics = Metrics() + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. -class MetricsInterceptor: + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: - def intercept(self, request: ChainedApiRequest) -> ApiResponse: - """ - An interceptor for adding an aws powertools metrics instance to the interceptor context - See: https://docs.powertools.aws.dev/lambda/python/latest/core/metrics/ + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + * Fields in \`self.additional_properties\` are added to the output dict. """ - operation_id = request.interceptor_context["operationId"] + _dict = self.model_dump( + by_alias=True, + exclude={ + "additional_properties", + }, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value - # Set the namespace if not set via environment variables - if metrics.namespace is None: - metrics.namespace = operation_id + return _dict - request.interceptor_context["metrics"] = metrics + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Dictionary from a dict""" - try: - metrics.add_dimension(name="operationId", value=operation_id) - return request.chain.next(request) - finally: - metrics.flush_metrics() + if obj is None: + return None - @staticmethod - def get_metrics(request: ChainedApiRequest) -> Metrics: - """ - Retrieve the metrics logger from the request - """ - if request.interceptor_context.get("metrics") is None: - raise Exception("No metrics found. Did you configure the MetricsInterceptor?") - return request.interceptor_context["metrics"] -", - "test_project/interceptors/powertools/tracer.py": "from aws_lambda_powertools import Tracer -from test_project.api.operation_config import ApiResponse, ChainedApiRequest + if not isinstance(obj, dict): + return cls.model_validate(obj) -tracer = Tracer() -is_cold_start = True + _obj = cls.model_validate({ + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) -class TracingInterceptor: - def __init__(self, add_response_as_metadata: bool = False): - self._add_response_as_metadata = add_response_as_metadata + return _obj - def intercept(self, request: ChainedApiRequest) -> ApiResponse: - """ - An interceptor for adding an aws powertools tracer to the interceptor context - See: https://docs.powertools.aws.dev/lambda/python/latest/core/tracer/ - """ - request.interceptor_context["tracer"] = tracer +", + "test_project/models/inline_enum200_response.py": "# coding: utf-8 - operation_id = request.interceptor_context["operationId"] +""" + Edge Cases - with tracer.provider.in_subsegment(name=f"## {operation_id}") as subsegment: - try: - result = request.chain.next(request) - tracer._add_response_as_metadata( - method_name=operation_id, - data=result, - subsegment=subsegment, - capture_response=self._add_response_as_metadata - ) - return result - except Exception as e: - tracer._add_full_exception_as_metadata( - method_name=operation_id, - error=e, - subsegment=subsegment, - capture_error=True - ) - raise - finally: - global is_cold_start - subsegment.put_annotation(key="ColdStart", value=is_cold_start) - is_cold_start = False + No description provided - @staticmethod - def get_tracer(request: ChainedApiRequest) -> Tracer: - """ - Retrieve the metrics logger from the request - """ - if request.interceptor_context.get("tracer") is None: - raise Exception("No tracer found. Did you configure the TracingInterceptor?") - return request.interceptor_context["tracer"] -", - "test_project/interceptors/response_headers.py": "from test_project.api.operation_config import ApiResponse, ChainedApiRequest -from typing import Dict + The version of the OpenAPI document: 1.0.0 -CORS_HEADERS = { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Headers": "*", -} + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 -def build_response_headers_interceptor(headers: Dict[str, str]): - """ - Build an interceptor for adding headers to the response. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class InlineEnum200Response(BaseModel): """ - def response_headers_interceptor(request: ChainedApiRequest) -> ApiResponse: - result = request.chain.next(request) - result.headers = { **headers, **(result.headers or {}) } - return result + InlineEnum200Response + """ # noqa: E501 + category: Optional[InlineEnum200ResponseCategoryEnum] = None + __properties: ClassVar[List[str]] = ["category"] - # Any error responses returned during request validation will include the headers - response_headers_interceptor.__type_safe_api_response_headers = headers - return response_headers_interceptor + model_config = { + "populate_by_name": True, + "validate_assignment": True + } -# Cors interceptor allows all origins and headers. Use build_response_headers_interceptors to customise -cors_interceptor = build_response_headers_interceptor(CORS_HEADERS) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) -", - "test_project/interceptors/try_catch.py": "from test_project.api.operation_config import ApiResponse, ChainedApiRequest -from test_project.response import Response + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of InlineEnum200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) -def try_catch_interceptor(request: ChainedApiRequest) -> ApiResponse: - """ - Interceptor for catching unhandled exceptions and returning a 500 error. - Uncaught exceptions which are ApiResponses will be returned, such that deeply nested code may return error - responses, eg: \`throw Response.not_found(...)\` - """ - try: - return request.chain.next(request) - except ApiResponse as response: - # If the error is a response, return it as the response - return response - except Exception as e: - if request.interceptor_context.get("logger") is not None: - request.interceptor_context.get("logger").exception("Interceptor caught exception") - else: - print("Interceptor caught exception") - print(e) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: + + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling \`to_dict()\` of category + if self.category: + _dict['category'] = self.category.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of InlineEnum200Response from a dict""" + + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "category": InlineEnum200ResponseCategoryEnum.from_dict(obj.get("category")) if obj.get("category") is not None else None + }) + return _obj - return Response.internal_failure({ "message": "Internal Error" }) ", - "test_project/models/__init__.py": "# coding: utf-8 + "test_project/models/inline_enum200_response_category_enum.py": "# coding: utf-8 -# flake8: noqa """ Edge Cases @@ -21342,13 +23282,41 @@ def try_catch_interceptor(request: ChainedApiRequest) -> ApiResponse: Do not edit the class manually. """ # noqa: E501 -# import models into model package -from test_project.models.inline_enum200_response import InlineEnum200Response -from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum -from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent -from test_project.models.my_enum import MyEnum +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class InlineEnum200ResponseCategoryEnum(str, Enum): + """ + InlineEnum200ResponseCategoryEnum + """ + + """ + allowed enum values + """ + FRUIT = 'fruit' + VEGETABLE = 'vegetable' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of InlineEnum200ResponseCategoryEnum from a JSON string""" + return cls(json.loads(json_str)) + + + ", - "test_project/models/inline_enum200_response.py": "# coding: utf-8 + "test_project/models/inline_request_body_request_content.py": "# coding: utf-8 """ Edge Cases @@ -21371,18 +23339,17 @@ from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool from decimal import Decimal from typing_extensions import Annotated, Literal -from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum try: from typing import Self except ImportError: from typing_extensions import Self -class InlineEnum200Response(BaseModel): +class InlineRequestBodyRequestContent(BaseModel): """ - InlineEnum200Response + InlineRequestBodyRequestContent """ # noqa: E501 - category: Optional[InlineEnum200ResponseCategoryEnum] = None - __properties: ClassVar[List[str]] = ["category"] + some_property: StrictStr = Field(alias="someProperty") + __properties: ClassVar[List[str]] = ["someProperty"] model_config = { @@ -21401,7 +23368,7 @@ class InlineEnum200Response(BaseModel): @classmethod def from_json(cls, json_str: str) -> Self: - """Create an instance of InlineEnum200Response from a JSON string""" + """Create an instance of InlineRequestBodyRequestContent from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -21420,14 +23387,11 @@ class InlineEnum200Response(BaseModel): }, exclude_none=True, ) - # override the default output from pydantic by calling \`to_dict()\` of category - if self.category: - _dict['category'] = self.category.to_dict() return _dict @classmethod def from_dict(cls, obj: Dict) -> Self: - """Create an instance of InlineEnum200Response from a dict""" + """Create an instance of InlineRequestBodyRequestContent from a dict""" if obj is None: return None @@ -21436,12 +23400,12 @@ class InlineEnum200Response(BaseModel): return cls.model_validate(obj) _obj = cls.model_validate({ - "category": InlineEnum200ResponseCategoryEnum.from_dict(obj.get("category")) if obj.get("category") is not None else None + "someProperty": obj.get("someProperty") }) return _obj ", - "test_project/models/inline_enum200_response_category_enum.py": "# coding: utf-8 + "test_project/models/my_enum.py": "# coding: utf-8 """ Edge Cases @@ -21469,26 +23433,27 @@ try: except ImportError: from typing_extensions import Self -class InlineEnum200ResponseCategoryEnum(str, Enum): +class MyEnum(str, Enum): """ - InlineEnum200ResponseCategoryEnum + MyEnum """ """ allowed enum values """ - FRUIT = 'fruit' - VEGETABLE = 'vegetable' + ONE = 'one' + TWO = 'two' + THREE = 'three' @classmethod def from_json(cls, json_str: str) -> Self: - """Create an instance of InlineEnum200ResponseCategoryEnum from a JSON string""" + """Create an instance of MyEnum from a JSON string""" return cls(json.loads(json_str)) ", - "test_project/models/inline_request_body_request_content.py": "# coding: utf-8 + "test_project/models/named_one_of.py": "# coding: utf-8 """ Edge Cases @@ -21516,12 +23481,12 @@ try: except ImportError: from typing_extensions import Self -class InlineRequestBodyRequestContent(BaseModel): +class NamedOneOf(BaseModel): """ - InlineRequestBodyRequestContent + NamedOneOf """ # noqa: E501 - some_property: StrictStr = Field(alias="someProperty") - __properties: ClassVar[List[str]] = ["someProperty"] + foo: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["foo"] model_config = { @@ -21540,7 +23505,7 @@ class InlineRequestBodyRequestContent(BaseModel): @classmethod def from_json(cls, json_str: str) -> Self: - """Create an instance of InlineRequestBodyRequestContent from a JSON string""" + """Create an instance of NamedOneOf from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -21563,7 +23528,7 @@ class InlineRequestBodyRequestContent(BaseModel): @classmethod def from_dict(cls, obj: Dict) -> Self: - """Create an instance of InlineRequestBodyRequestContent from a dict""" + """Create an instance of NamedOneOf from a dict""" if obj is None: return None @@ -21572,12 +23537,12 @@ class InlineRequestBodyRequestContent(BaseModel): return cls.model_validate(obj) _obj = cls.model_validate({ - "someProperty": obj.get("someProperty") + "foo": obj.get("foo") }) return _obj ", - "test_project/models/my_enum.py": "# coding: utf-8 + "test_project/models/named_one_of_union.py": "# coding: utf-8 """ Edge Cases @@ -21600,29 +23565,212 @@ from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool from decimal import Decimal from typing_extensions import Annotated, Literal +from test_project.models.another_named_one_of import AnotherNamedOneOf +from test_project.models.named_one_of import NamedOneOf try: from typing import Self except ImportError: from typing_extensions import Self -class MyEnum(str, Enum): - """ - MyEnum - """ +NAMEDONEOFUNION_ONE_OF_SCHEMAS = ["NamedOneOf", "AnotherNamedOneOf"] +class NamedOneOfUnion(BaseModel): """ - allowed enum values + NamedOneOfUnion + """ # noqa: E501 + # data type: NamedOneOf + oneof_schema_1_validator: Optional[NamedOneOf] = None + # data type: AnotherNamedOneOf + oneof_schema_2_validator: Optional[AnotherNamedOneOf] = None + actual_instance: Optional[Union[NamedOneOf, AnotherNamedOneOf]] = None + one_of_schemas: List[str] = Literal["NamedOneOf", "AnotherNamedOneOf"] + + model_config = { + "validate_assignment": True + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set \`actual_instance\`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = NamedOneOfUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: NamedOneOf + if not isinstance(v, NamedOneOf): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`NamedOneOf\`") + else: + match += 1 + # validate data type: AnotherNamedOneOf + if not isinstance(v, AnotherNamedOneOf): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`AnotherNamedOneOf\`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting \`actual_instance\` in NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting \`actual_instance\` in NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into NamedOneOf + try: + instance.actual_instance = NamedOneOf.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into AnotherNamedOneOf + try: + instance.actual_instance = AnotherNamedOneOf.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + +", + "test_project/models/some_object.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class SomeObject(BaseModel): """ - ONE = 'one' - TWO = 'two' - THREE = 'three' + SomeObject + """ # noqa: E501 + a: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["a"] + + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) @classmethod def from_json(cls, json_str: str) -> Self: - """Create an instance of MyEnum from a JSON string""" - return cls(json.loads(json_str)) + """Create an instance of SomeObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: + + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of SomeObject from a dict""" + + if obj is None: + return None + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "a": obj.get("a") + }) + return _obj ", "test_project/py.typed": "", diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap index 82ef4cbab..a9e4306ae 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap @@ -8237,10 +8237,17 @@ src/apis/DefaultApi.ts src/apis/index.ts src/models/index.ts src/models/model-utils.ts +src/models/AdditionalPropertiesResponse.ts +src/models/AnotherNamedOneOf.ts +src/models/ArrayOfOneOfs.ts +src/models/Dictionary.ts src/models/InlineEnum200Response.ts src/models/InlineEnum200ResponseCategoryEnum.ts src/models/InlineRequestBodyRequestContent.ts -src/models/MyEnum.ts", +src/models/MyEnum.ts +src/models/NamedOneOf.ts +src/models/NamedOneOfUnion.ts +src/models/SomeObject.ts", "src/apis/DefaultApi.ts": "/* tslint:disable */ /* eslint-disable */ /** @@ -8256,19 +8263,29 @@ src/models/MyEnum.ts", import * as runtime from '../runtime'; import type { + AdditionalPropertiesResponse, + ArrayOfOneOfs, InlineEnum200Response, InlineRequestBodyRequestContent, MyEnum, + NamedOneOfUnion, } from '../models'; import { + AdditionalPropertiesResponseFromJSON, + AdditionalPropertiesResponseToJSON, + ArrayOfOneOfsFromJSON, + ArrayOfOneOfsToJSON, InlineEnum200ResponseFromJSON, InlineEnum200ResponseToJSON, InlineRequestBodyRequestContentFromJSON, InlineRequestBodyRequestContentToJSON, MyEnumFromJSON, MyEnumToJSON, + NamedOneOfUnionFromJSON, + NamedOneOfUnionToJSON, } from '../models'; + export interface ArrayRequestParametersRequest { myStringArrayRequestParams?: Array; myEnumArrayRequestParams?: Array; @@ -8282,10 +8299,12 @@ export interface ArrayRequestParametersRequest { } + export interface InlineRequestBodyRequest { inlineRequestBodyRequestContent?: InlineRequestBodyRequestContent; } + export interface ReservedKeywordsRequest { _with?: string; _if?: string; @@ -8296,6 +8315,35 @@ export interface ReservedKeywordsRequest { * */ export class DefaultApi extends runtime.BaseAPI { + /** + * + */ + async arrayOfOneOfsRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + + const headerParameters: runtime.HTTPHeaders = {}; + + + + const response = await this.request({ + path: \`/array-of-one-ofs\`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ArrayOfOneOfsFromJSON(jsonValue)); + } + + /** + * + */ + async arrayOfOneOfs(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.arrayOfOneOfsRaw(initOverrides); + return await response.value(); + } + /** * */ @@ -8360,6 +8408,35 @@ export class DefaultApi extends runtime.BaseAPI { await this.arrayRequestParametersRaw(requestParameters, initOverrides); } + /** + * + */ + async dictionaryRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + + const headerParameters: runtime.HTTPHeaders = {}; + + + + const response = await this.request({ + path: \`/additional-properties\`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => AdditionalPropertiesResponseFromJSON(jsonValue)); + } + + /** + * + */ + async dictionary(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.dictionaryRaw(initOverrides); + return await response.value(); + } + /** * */ @@ -8419,6 +8496,35 @@ export class DefaultApi extends runtime.BaseAPI { await this.inlineRequestBodyRaw(requestParameters, initOverrides); } + /** + * + */ + async namedOneOfRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + + const headerParameters: runtime.HTTPHeaders = {}; + + + + const response = await this.request({ + path: \`/named-one-of\`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => NamedOneOfUnionFromJSON(jsonValue)); + } + + /** + * + */ + async namedOneOf(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.namedOneOfRaw(initOverrides); + return await response.value(); + } + /** * */ @@ -8464,6 +8570,18 @@ export class DefaultApi extends runtime.BaseAPI { ", "src/apis/DefaultApi/OperationConfig.ts": "// Import models import { + AdditionalPropertiesResponse, + AdditionalPropertiesResponseFromJSON, + AdditionalPropertiesResponseToJSON, + AnotherNamedOneOf, + AnotherNamedOneOfFromJSON, + AnotherNamedOneOfToJSON, + ArrayOfOneOfs, + ArrayOfOneOfsFromJSON, + ArrayOfOneOfsToJSON, + Dictionary, + DictionaryFromJSON, + DictionaryToJSON, InlineEnum200Response, InlineEnum200ResponseFromJSON, InlineEnum200ResponseToJSON, @@ -8476,6 +8594,15 @@ import { MyEnum, MyEnumFromJSON, MyEnumToJSON, + NamedOneOf, + NamedOneOfFromJSON, + NamedOneOfToJSON, + NamedOneOfUnion, + NamedOneOfUnionFromJSON, + NamedOneOfUnionToJSON, + SomeObject, + SomeObjectFromJSON, + SomeObjectToJSON, } from '../../models'; // Import request parameter interfaces import { @@ -8489,19 +8616,32 @@ import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda // Generic type for object keyed by operation names export interface OperationConfig { + arrayOfOneOfs: T; arrayRequestParameters: T; + dictionary: T; inlineEnum: T; inlineRequestBody: T; + namedOneOf: T; reservedKeywords: T; } // Look up path and http method for a given operation name export const OperationLookup = { + arrayOfOneOfs: { + path: '/array-of-one-ofs', + method: 'POST', + contentTypes: ['application/json'], + }, arrayRequestParameters: { path: '/array-request-parameters', method: 'GET', contentTypes: ['application/json'], }, + dictionary: { + path: '/additional-properties', + method: 'POST', + contentTypes: ['application/json'], + }, inlineEnum: { path: '/inline-enum', method: 'GET', @@ -8512,6 +8652,11 @@ export const OperationLookup = { method: 'POST', contentTypes: ['application/json'], }, + namedOneOf: { + path: '/named-one-of', + method: 'POST', + contentTypes: ['application/json'], + }, reservedKeywords: { path: '/reserved-keywords', method: 'GET', @@ -8633,7 +8778,7 @@ const extractResponseHeadersFromInterceptors = (interceptors: any[]): { [key: st }), {} as { [key: string]: string }); }; -export type OperationIds = | 'arrayRequestParameters' | 'inlineEnum' | 'inlineRequestBody' | 'reservedKeywords'; +export type OperationIds = | 'arrayOfOneOfs' | 'arrayRequestParameters' | 'dictionary' | 'inlineEnum' | 'inlineRequestBody' | 'namedOneOf' | 'reservedKeywords'; export type OperationApiGatewayProxyResult = APIGatewayProxyResult & { __operationId?: T }; // Api gateway lambda handler type @@ -8710,41 +8855,32 @@ const buildHandlerChain = ( }; /** - * Path, Query and Header parameters for ArrayRequestParameters + * Path, Query and Header parameters for ArrayOfOneOfs */ -export interface ArrayRequestParametersRequestParameters { - readonly myStringArrayRequestParams?: Array; - readonly myEnumArrayRequestParams?: Array; - readonly myIntegerArrayRequestParams?: Array; - readonly myLongArrayRequestParams?: Array; - readonly myInt32ArrayRequestParams?: Array; - readonly myNumberArrayRequestParams?: Array; - readonly myFloatArrayRequestParams?: Array; - readonly myDoubleArrayRequestParams?: Array; - readonly myEnumRequestParam?: MyEnum; +export interface ArrayOfOneOfsRequestParameters { } /** - * Request body parameter for ArrayRequestParameters + * Request body parameter for ArrayOfOneOfs */ -export type ArrayRequestParametersRequestBody = never; +export type ArrayOfOneOfsRequestBody = never; -export type ArrayRequestParameters200OperationResponse = OperationResponse<200, undefined>; +export type ArrayOfOneOfs200OperationResponse = OperationResponse<200, ArrayOfOneOfs>; -export type ArrayRequestParametersOperationResponses = | ArrayRequestParameters200OperationResponse ; +export type ArrayOfOneOfsOperationResponses = | ArrayOfOneOfs200OperationResponse ; // Type that the handler function provided to the wrapper must conform to -export type ArrayRequestParametersHandlerFunction = LambdaHandlerFunction; -export type ArrayRequestParametersChainedHandlerFunction = ChainedLambdaHandlerFunction; -export type ArrayRequestParametersChainedRequestInput = ChainedRequestInput; +export type ArrayOfOneOfsHandlerFunction = LambdaHandlerFunction; +export type ArrayOfOneOfsChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type ArrayOfOneOfsChainedRequestInput = ChainedRequestInput; /** - * Lambda handler wrapper to provide typed interface for the implementation of arrayRequestParameters + * Lambda handler wrapper to provide typed interface for the implementation of arrayOfOneOfs */ -export const arrayRequestParametersHandler = ( - ...handlers: [ArrayRequestParametersChainedHandlerFunction, ...ArrayRequestParametersChainedHandlerFunction[]] -): OperationApiGatewayLambdaHandler<'arrayRequestParameters'> => async (event: any, context: any, _callback?: any, additionalInterceptors: ArrayRequestParametersChainedHandlerFunction[] = []): Promise => { - const operationId = "arrayRequestParameters"; +export const arrayOfOneOfsHandler = ( + ...handlers: [ArrayOfOneOfsChainedHandlerFunction, ...ArrayOfOneOfsChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'arrayOfOneOfs'> => async (event: any, context: any, _callback?: any, additionalInterceptors: ArrayOfOneOfsChainedHandlerFunction[] = []): Promise => { + const operationId = "arrayOfOneOfs"; const rawSingleValueParameters = decodeRequestParameters({ ...(event.pathParameters || {}), @@ -8760,6 +8896,7 @@ export const arrayRequestParametersHandler = ( let marshalledBody = responseBody; switch(statusCode) { case 200: + marshalledBody = JSON.stringify(ArrayOfOneOfsToJSON(marshalledBody)); break; default: break; @@ -8779,19 +8916,10 @@ export const arrayRequestParametersHandler = ( return headers; }; - let requestParameters: ArrayRequestParametersRequestParameters | undefined = undefined; + let requestParameters: ArrayOfOneOfsRequestParameters | undefined = undefined; try { requestParameters = { - myStringArrayRequestParams: coerceParameter("my-string-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myEnumArrayRequestParams: coerceParameter("my-enum-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myIntegerArrayRequestParams: coerceParameter("my-integer-array-request-params", "Array", true || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myLongArrayRequestParams: coerceParameter("my-long-array-request-params", "Array", true || true || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myInt32ArrayRequestParams: coerceParameter("my-int32-array-request-params", "Array", true || false || true, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myNumberArrayRequestParams: coerceParameter("my-number-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myFloatArrayRequestParams: coerceParameter("my-float-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myDoubleArrayRequestParams: coerceParameter("my-double-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, - myEnumRequestParam: coerceParameter("my-enum-request-param", "MyEnum", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as MyEnum | undefined, }; } catch (e: any) { @@ -8813,7 +8941,7 @@ export const arrayRequestParametersHandler = ( const demarshal = (bodyString: string): any => { return {}; }; - const body = parseBody(event.body, demarshal, ['application/json']) as ArrayRequestParametersRequestBody; + const body = parseBody(event.body, demarshal, ['application/json']) as ArrayOfOneOfsRequestBody; const chain = buildHandlerChain(...additionalInterceptors, ...handlers); const response = await chain.next({ @@ -8836,32 +8964,41 @@ export const arrayRequestParametersHandler = ( }; }; /** - * Path, Query and Header parameters for InlineEnum + * Path, Query and Header parameters for ArrayRequestParameters */ -export interface InlineEnumRequestParameters { +export interface ArrayRequestParametersRequestParameters { + readonly myStringArrayRequestParams?: Array; + readonly myEnumArrayRequestParams?: Array; + readonly myIntegerArrayRequestParams?: Array; + readonly myLongArrayRequestParams?: Array; + readonly myInt32ArrayRequestParams?: Array; + readonly myNumberArrayRequestParams?: Array; + readonly myFloatArrayRequestParams?: Array; + readonly myDoubleArrayRequestParams?: Array; + readonly myEnumRequestParam?: MyEnum; } /** - * Request body parameter for InlineEnum + * Request body parameter for ArrayRequestParameters */ -export type InlineEnumRequestBody = never; +export type ArrayRequestParametersRequestBody = never; -export type InlineEnum200OperationResponse = OperationResponse<200, InlineEnum200Response>; +export type ArrayRequestParameters200OperationResponse = OperationResponse<200, undefined>; -export type InlineEnumOperationResponses = | InlineEnum200OperationResponse ; +export type ArrayRequestParametersOperationResponses = | ArrayRequestParameters200OperationResponse ; // Type that the handler function provided to the wrapper must conform to -export type InlineEnumHandlerFunction = LambdaHandlerFunction; -export type InlineEnumChainedHandlerFunction = ChainedLambdaHandlerFunction; -export type InlineEnumChainedRequestInput = ChainedRequestInput; +export type ArrayRequestParametersHandlerFunction = LambdaHandlerFunction; +export type ArrayRequestParametersChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type ArrayRequestParametersChainedRequestInput = ChainedRequestInput; /** - * Lambda handler wrapper to provide typed interface for the implementation of inlineEnum + * Lambda handler wrapper to provide typed interface for the implementation of arrayRequestParameters */ -export const inlineEnumHandler = ( - ...handlers: [InlineEnumChainedHandlerFunction, ...InlineEnumChainedHandlerFunction[]] -): OperationApiGatewayLambdaHandler<'inlineEnum'> => async (event: any, context: any, _callback?: any, additionalInterceptors: InlineEnumChainedHandlerFunction[] = []): Promise => { - const operationId = "inlineEnum"; +export const arrayRequestParametersHandler = ( + ...handlers: [ArrayRequestParametersChainedHandlerFunction, ...ArrayRequestParametersChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'arrayRequestParameters'> => async (event: any, context: any, _callback?: any, additionalInterceptors: ArrayRequestParametersChainedHandlerFunction[] = []): Promise => { + const operationId = "arrayRequestParameters"; const rawSingleValueParameters = decodeRequestParameters({ ...(event.pathParameters || {}), @@ -8877,7 +9014,6 @@ export const inlineEnumHandler = ( let marshalledBody = responseBody; switch(statusCode) { case 200: - marshalledBody = JSON.stringify(InlineEnum200ResponseToJSON(marshalledBody)); break; default: break; @@ -8897,10 +9033,19 @@ export const inlineEnumHandler = ( return headers; }; - let requestParameters: InlineEnumRequestParameters | undefined = undefined; + let requestParameters: ArrayRequestParametersRequestParameters | undefined = undefined; try { requestParameters = { + myStringArrayRequestParams: coerceParameter("my-string-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myEnumArrayRequestParams: coerceParameter("my-enum-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myIntegerArrayRequestParams: coerceParameter("my-integer-array-request-params", "Array", true || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myLongArrayRequestParams: coerceParameter("my-long-array-request-params", "Array", true || true || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myInt32ArrayRequestParams: coerceParameter("my-int32-array-request-params", "Array", true || false || true, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myNumberArrayRequestParams: coerceParameter("my-number-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myFloatArrayRequestParams: coerceParameter("my-float-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myDoubleArrayRequestParams: coerceParameter("my-double-array-request-params", "Array", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as Array | undefined, + myEnumRequestParam: coerceParameter("my-enum-request-param", "MyEnum", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as MyEnum | undefined, }; } catch (e: any) { @@ -8922,7 +9067,7 @@ export const inlineEnumHandler = ( const demarshal = (bodyString: string): any => { return {}; }; - const body = parseBody(event.body, demarshal, ['application/json']) as InlineEnumRequestBody; + const body = parseBody(event.body, demarshal, ['application/json']) as ArrayRequestParametersRequestBody; const chain = buildHandlerChain(...additionalInterceptors, ...handlers); const response = await chain.next({ @@ -8945,32 +9090,32 @@ export const inlineEnumHandler = ( }; }; /** - * Path, Query and Header parameters for InlineRequestBody + * Path, Query and Header parameters for Dictionary */ -export interface InlineRequestBodyRequestParameters { +export interface DictionaryRequestParameters { } /** - * Request body parameter for InlineRequestBody + * Request body parameter for Dictionary */ -export type InlineRequestBodyRequestBody = InlineRequestBodyRequestContent; +export type DictionaryRequestBody = never; -export type InlineRequestBody204OperationResponse = OperationResponse<204, undefined>; +export type Dictionary200OperationResponse = OperationResponse<200, AdditionalPropertiesResponse>; -export type InlineRequestBodyOperationResponses = | InlineRequestBody204OperationResponse ; +export type DictionaryOperationResponses = | Dictionary200OperationResponse ; // Type that the handler function provided to the wrapper must conform to -export type InlineRequestBodyHandlerFunction = LambdaHandlerFunction; -export type InlineRequestBodyChainedHandlerFunction = ChainedLambdaHandlerFunction; -export type InlineRequestBodyChainedRequestInput = ChainedRequestInput; +export type DictionaryHandlerFunction = LambdaHandlerFunction; +export type DictionaryChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type DictionaryChainedRequestInput = ChainedRequestInput; /** - * Lambda handler wrapper to provide typed interface for the implementation of inlineRequestBody + * Lambda handler wrapper to provide typed interface for the implementation of dictionary */ -export const inlineRequestBodyHandler = ( - ...handlers: [InlineRequestBodyChainedHandlerFunction, ...InlineRequestBodyChainedHandlerFunction[]] -): OperationApiGatewayLambdaHandler<'inlineRequestBody'> => async (event: any, context: any, _callback?: any, additionalInterceptors: InlineRequestBodyChainedHandlerFunction[] = []): Promise => { - const operationId = "inlineRequestBody"; +export const dictionaryHandler = ( + ...handlers: [DictionaryChainedHandlerFunction, ...DictionaryChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'dictionary'> => async (event: any, context: any, _callback?: any, additionalInterceptors: DictionaryChainedHandlerFunction[] = []): Promise => { + const operationId = "dictionary"; const rawSingleValueParameters = decodeRequestParameters({ ...(event.pathParameters || {}), @@ -8985,7 +9130,8 @@ export const inlineRequestBodyHandler = ( const marshal = (statusCode: number, responseBody: any): string => { let marshalledBody = responseBody; switch(statusCode) { - case 204: + case 200: + marshalledBody = JSON.stringify(AdditionalPropertiesResponseToJSON(marshalledBody)); break; default: break; @@ -9005,7 +9151,7 @@ export const inlineRequestBodyHandler = ( return headers; }; - let requestParameters: InlineRequestBodyRequestParameters | undefined = undefined; + let requestParameters: DictionaryRequestParameters | undefined = undefined; try { requestParameters = { @@ -9028,9 +9174,9 @@ export const inlineRequestBodyHandler = ( } const demarshal = (bodyString: string): any => { - return InlineRequestBodyRequestContentFromJSON(JSON.parse(bodyString)); + return {}; }; - const body = parseBody(event.body, demarshal, ['application/json']) as InlineRequestBodyRequestBody; + const body = parseBody(event.body, demarshal, ['application/json']) as DictionaryRequestBody; const chain = buildHandlerChain(...additionalInterceptors, ...handlers); const response = await chain.next({ @@ -9053,35 +9199,32 @@ export const inlineRequestBodyHandler = ( }; }; /** - * Path, Query and Header parameters for ReservedKeywords + * Path, Query and Header parameters for InlineEnum */ -export interface ReservedKeywordsRequestParameters { - readonly _with?: string; - readonly _if?: string; - readonly _class?: string; +export interface InlineEnumRequestParameters { } /** - * Request body parameter for ReservedKeywords + * Request body parameter for InlineEnum */ -export type ReservedKeywordsRequestBody = never; +export type InlineEnumRequestBody = never; -export type ReservedKeywords200OperationResponse = OperationResponse<200, undefined>; +export type InlineEnum200OperationResponse = OperationResponse<200, InlineEnum200Response>; -export type ReservedKeywordsOperationResponses = | ReservedKeywords200OperationResponse ; +export type InlineEnumOperationResponses = | InlineEnum200OperationResponse ; // Type that the handler function provided to the wrapper must conform to -export type ReservedKeywordsHandlerFunction = LambdaHandlerFunction; -export type ReservedKeywordsChainedHandlerFunction = ChainedLambdaHandlerFunction; -export type ReservedKeywordsChainedRequestInput = ChainedRequestInput; +export type InlineEnumHandlerFunction = LambdaHandlerFunction; +export type InlineEnumChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type InlineEnumChainedRequestInput = ChainedRequestInput; /** - * Lambda handler wrapper to provide typed interface for the implementation of reservedKeywords + * Lambda handler wrapper to provide typed interface for the implementation of inlineEnum */ -export const reservedKeywordsHandler = ( - ...handlers: [ReservedKeywordsChainedHandlerFunction, ...ReservedKeywordsChainedHandlerFunction[]] -): OperationApiGatewayLambdaHandler<'reservedKeywords'> => async (event: any, context: any, _callback?: any, additionalInterceptors: ReservedKeywordsChainedHandlerFunction[] = []): Promise => { - const operationId = "reservedKeywords"; +export const inlineEnumHandler = ( + ...handlers: [InlineEnumChainedHandlerFunction, ...InlineEnumChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'inlineEnum'> => async (event: any, context: any, _callback?: any, additionalInterceptors: InlineEnumChainedHandlerFunction[] = []): Promise => { + const operationId = "inlineEnum"; const rawSingleValueParameters = decodeRequestParameters({ ...(event.pathParameters || {}), @@ -9097,6 +9240,7 @@ export const reservedKeywordsHandler = ( let marshalledBody = responseBody; switch(statusCode) { case 200: + marshalledBody = JSON.stringify(InlineEnum200ResponseToJSON(marshalledBody)); break; default: break; @@ -9116,13 +9260,10 @@ export const reservedKeywordsHandler = ( return headers; }; - let requestParameters: ReservedKeywordsRequestParameters | undefined = undefined; + let requestParameters: InlineEnumRequestParameters | undefined = undefined; try { requestParameters = { - _with: coerceParameter("with", "string", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as string | undefined, - _if: coerceParameter("if", "string", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as string | undefined, - _class: coerceParameter("class", "string", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as string | undefined, }; } catch (e: any) { @@ -9144,7 +9285,7 @@ export const reservedKeywordsHandler = ( const demarshal = (bodyString: string): any => { return {}; }; - const body = parseBody(event.body, demarshal, ['application/json']) as ReservedKeywordsRequestBody; + const body = parseBody(event.body, demarshal, ['application/json']) as InlineEnumRequestBody; const chain = buildHandlerChain(...additionalInterceptors, ...handlers); const response = await chain.next({ @@ -9166,31 +9307,365 @@ export const reservedKeywordsHandler = ( body: response.body ? marshal(response.statusCode, response.body) : '', }; }; - -export interface HandlerRouterHandlers { - readonly arrayRequestParameters: OperationApiGatewayLambdaHandler<'arrayRequestParameters'>; - readonly inlineEnum: OperationApiGatewayLambdaHandler<'inlineEnum'>; - readonly inlineRequestBody: OperationApiGatewayLambdaHandler<'inlineRequestBody'>; - readonly reservedKeywords: OperationApiGatewayLambdaHandler<'reservedKeywords'>; +/** + * Path, Query and Header parameters for InlineRequestBody + */ +export interface InlineRequestBodyRequestParameters { } -export type AnyOperationRequestParameters = | ArrayRequestParametersRequestParameters| InlineEnumRequestParameters| InlineRequestBodyRequestParameters| ReservedKeywordsRequestParameters; -export type AnyOperationRequestBodies = | ArrayRequestParametersRequestBody| InlineEnumRequestBody| InlineRequestBodyRequestBody| ReservedKeywordsRequestBody; -export type AnyOperationResponses = | ArrayRequestParametersOperationResponses| InlineEnumOperationResponses| InlineRequestBodyOperationResponses| ReservedKeywordsOperationResponses; +/** + * Request body parameter for InlineRequestBody + */ +export type InlineRequestBodyRequestBody = InlineRequestBodyRequestContent; -export interface HandlerRouterProps< - RequestParameters, - RequestBody, - Response extends AnyOperationResponses -> { - /** - * Interceptors to apply to all handlers - */ - readonly interceptors?: ChainedLambdaHandlerFunction< - RequestParameters, - RequestBody, - Response - >[]; +export type InlineRequestBody204OperationResponse = OperationResponse<204, undefined>; + +export type InlineRequestBodyOperationResponses = | InlineRequestBody204OperationResponse ; + +// Type that the handler function provided to the wrapper must conform to +export type InlineRequestBodyHandlerFunction = LambdaHandlerFunction; +export type InlineRequestBodyChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type InlineRequestBodyChainedRequestInput = ChainedRequestInput; + +/** + * Lambda handler wrapper to provide typed interface for the implementation of inlineRequestBody + */ +export const inlineRequestBodyHandler = ( + ...handlers: [InlineRequestBodyChainedHandlerFunction, ...InlineRequestBodyChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'inlineRequestBody'> => async (event: any, context: any, _callback?: any, additionalInterceptors: InlineRequestBodyChainedHandlerFunction[] = []): Promise => { + const operationId = "inlineRequestBody"; + + const rawSingleValueParameters = decodeRequestParameters({ + ...(event.pathParameters || {}), + ...(event.queryStringParameters || {}), + ...(event.headers || {}), + }) as { [key: string]: string | undefined }; + const rawMultiValueParameters = decodeRequestParameters({ + ...(event.multiValueQueryStringParameters || {}), + ...(event.multiValueHeaders || {}), + }) as { [key: string]: string[] | undefined }; + + const marshal = (statusCode: number, responseBody: any): string => { + let marshalledBody = responseBody; + switch(statusCode) { + case 204: + break; + default: + break; + } + + return marshalledBody; + }; + + const errorHeaders = (statusCode: number): { [key: string]: string } => { + let headers = {}; + + switch(statusCode) { + default: + break; + } + + return headers; + }; + + let requestParameters: InlineRequestBodyRequestParameters | undefined = undefined; + + try { + requestParameters = { + + }; + } catch (e: any) { + const res = { + statusCode: 400, + body: { message: e.message }, + headers: extractResponseHeadersFromInterceptors(handlers), + }; + return { + ...res, + headers: { + ...errorHeaders(res.statusCode), + ...res.headers, + }, + body: res.body ? marshal(res.statusCode, res.body) : '', + }; + } + + const demarshal = (bodyString: string): any => { + return InlineRequestBodyRequestContentFromJSON(JSON.parse(bodyString)); + }; + const body = parseBody(event.body, demarshal, ['application/json']) as InlineRequestBodyRequestBody; + + const chain = buildHandlerChain(...additionalInterceptors, ...handlers); + const response = await chain.next({ + input: { + requestParameters, + body, + }, + event, + context, + interceptorContext: { operationId }, + }); + + return { + ...response, + headers: { + ...errorHeaders(response.statusCode), + ...response.headers, + }, + body: response.body ? marshal(response.statusCode, response.body) : '', + }; +}; +/** + * Path, Query and Header parameters for NamedOneOf + */ +export interface NamedOneOfRequestParameters { +} + +/** + * Request body parameter for NamedOneOf + */ +export type NamedOneOfRequestBody = never; + +export type NamedOneOf200OperationResponse = OperationResponse<200, NamedOneOfUnion>; + +export type NamedOneOfOperationResponses = | NamedOneOf200OperationResponse ; + +// Type that the handler function provided to the wrapper must conform to +export type NamedOneOfHandlerFunction = LambdaHandlerFunction; +export type NamedOneOfChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type NamedOneOfChainedRequestInput = ChainedRequestInput; + +/** + * Lambda handler wrapper to provide typed interface for the implementation of namedOneOf + */ +export const namedOneOfHandler = ( + ...handlers: [NamedOneOfChainedHandlerFunction, ...NamedOneOfChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'namedOneOf'> => async (event: any, context: any, _callback?: any, additionalInterceptors: NamedOneOfChainedHandlerFunction[] = []): Promise => { + const operationId = "namedOneOf"; + + const rawSingleValueParameters = decodeRequestParameters({ + ...(event.pathParameters || {}), + ...(event.queryStringParameters || {}), + ...(event.headers || {}), + }) as { [key: string]: string | undefined }; + const rawMultiValueParameters = decodeRequestParameters({ + ...(event.multiValueQueryStringParameters || {}), + ...(event.multiValueHeaders || {}), + }) as { [key: string]: string[] | undefined }; + + const marshal = (statusCode: number, responseBody: any): string => { + let marshalledBody = responseBody; + switch(statusCode) { + case 200: + marshalledBody = JSON.stringify(NamedOneOfUnionToJSON(marshalledBody)); + break; + default: + break; + } + + return marshalledBody; + }; + + const errorHeaders = (statusCode: number): { [key: string]: string } => { + let headers = {}; + + switch(statusCode) { + default: + break; + } + + return headers; + }; + + let requestParameters: NamedOneOfRequestParameters | undefined = undefined; + + try { + requestParameters = { + + }; + } catch (e: any) { + const res = { + statusCode: 400, + body: { message: e.message }, + headers: extractResponseHeadersFromInterceptors(handlers), + }; + return { + ...res, + headers: { + ...errorHeaders(res.statusCode), + ...res.headers, + }, + body: res.body ? marshal(res.statusCode, res.body) : '', + }; + } + + const demarshal = (bodyString: string): any => { + return {}; + }; + const body = parseBody(event.body, demarshal, ['application/json']) as NamedOneOfRequestBody; + + const chain = buildHandlerChain(...additionalInterceptors, ...handlers); + const response = await chain.next({ + input: { + requestParameters, + body, + }, + event, + context, + interceptorContext: { operationId }, + }); + + return { + ...response, + headers: { + ...errorHeaders(response.statusCode), + ...response.headers, + }, + body: response.body ? marshal(response.statusCode, response.body) : '', + }; +}; +/** + * Path, Query and Header parameters for ReservedKeywords + */ +export interface ReservedKeywordsRequestParameters { + readonly _with?: string; + readonly _if?: string; + readonly _class?: string; +} + +/** + * Request body parameter for ReservedKeywords + */ +export type ReservedKeywordsRequestBody = never; + +export type ReservedKeywords200OperationResponse = OperationResponse<200, undefined>; + +export type ReservedKeywordsOperationResponses = | ReservedKeywords200OperationResponse ; + +// Type that the handler function provided to the wrapper must conform to +export type ReservedKeywordsHandlerFunction = LambdaHandlerFunction; +export type ReservedKeywordsChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type ReservedKeywordsChainedRequestInput = ChainedRequestInput; + +/** + * Lambda handler wrapper to provide typed interface for the implementation of reservedKeywords + */ +export const reservedKeywordsHandler = ( + ...handlers: [ReservedKeywordsChainedHandlerFunction, ...ReservedKeywordsChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'reservedKeywords'> => async (event: any, context: any, _callback?: any, additionalInterceptors: ReservedKeywordsChainedHandlerFunction[] = []): Promise => { + const operationId = "reservedKeywords"; + + const rawSingleValueParameters = decodeRequestParameters({ + ...(event.pathParameters || {}), + ...(event.queryStringParameters || {}), + ...(event.headers || {}), + }) as { [key: string]: string | undefined }; + const rawMultiValueParameters = decodeRequestParameters({ + ...(event.multiValueQueryStringParameters || {}), + ...(event.multiValueHeaders || {}), + }) as { [key: string]: string[] | undefined }; + + const marshal = (statusCode: number, responseBody: any): string => { + let marshalledBody = responseBody; + switch(statusCode) { + case 200: + break; + default: + break; + } + + return marshalledBody; + }; + + const errorHeaders = (statusCode: number): { [key: string]: string } => { + let headers = {}; + + switch(statusCode) { + default: + break; + } + + return headers; + }; + + let requestParameters: ReservedKeywordsRequestParameters | undefined = undefined; + + try { + requestParameters = { + _with: coerceParameter("with", "string", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as string | undefined, + _if: coerceParameter("if", "string", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as string | undefined, + _class: coerceParameter("class", "string", false || false || false, rawSingleValueParameters, rawMultiValueParameters, false) as string | undefined, + + }; + } catch (e: any) { + const res = { + statusCode: 400, + body: { message: e.message }, + headers: extractResponseHeadersFromInterceptors(handlers), + }; + return { + ...res, + headers: { + ...errorHeaders(res.statusCode), + ...res.headers, + }, + body: res.body ? marshal(res.statusCode, res.body) : '', + }; + } + + const demarshal = (bodyString: string): any => { + return {}; + }; + const body = parseBody(event.body, demarshal, ['application/json']) as ReservedKeywordsRequestBody; + + const chain = buildHandlerChain(...additionalInterceptors, ...handlers); + const response = await chain.next({ + input: { + requestParameters, + body, + }, + event, + context, + interceptorContext: { operationId }, + }); + + return { + ...response, + headers: { + ...errorHeaders(response.statusCode), + ...response.headers, + }, + body: response.body ? marshal(response.statusCode, response.body) : '', + }; +}; + +export interface HandlerRouterHandlers { + readonly arrayOfOneOfs: OperationApiGatewayLambdaHandler<'arrayOfOneOfs'>; + readonly arrayRequestParameters: OperationApiGatewayLambdaHandler<'arrayRequestParameters'>; + readonly dictionary: OperationApiGatewayLambdaHandler<'dictionary'>; + readonly inlineEnum: OperationApiGatewayLambdaHandler<'inlineEnum'>; + readonly inlineRequestBody: OperationApiGatewayLambdaHandler<'inlineRequestBody'>; + readonly namedOneOf: OperationApiGatewayLambdaHandler<'namedOneOf'>; + readonly reservedKeywords: OperationApiGatewayLambdaHandler<'reservedKeywords'>; +} + +export type AnyOperationRequestParameters = | ArrayOfOneOfsRequestParameters| ArrayRequestParametersRequestParameters| DictionaryRequestParameters| InlineEnumRequestParameters| InlineRequestBodyRequestParameters| NamedOneOfRequestParameters| ReservedKeywordsRequestParameters; +export type AnyOperationRequestBodies = | ArrayOfOneOfsRequestBody| ArrayRequestParametersRequestBody| DictionaryRequestBody| InlineEnumRequestBody| InlineRequestBodyRequestBody| NamedOneOfRequestBody| ReservedKeywordsRequestBody; +export type AnyOperationResponses = | ArrayOfOneOfsOperationResponses| ArrayRequestParametersOperationResponses| DictionaryOperationResponses| InlineEnumOperationResponses| InlineRequestBodyOperationResponses| NamedOneOfOperationResponses| ReservedKeywordsOperationResponses; + +export interface HandlerRouterProps< + RequestParameters, + RequestBody, + Response extends AnyOperationResponses +> { + /** + * Interceptors to apply to all handlers + */ + readonly interceptors?: ChainedLambdaHandlerFunction< + RequestParameters, + RequestBody, + Response + >[]; /** * Handlers to register for each operation @@ -9469,57 +9944,326 @@ export class TracingInterceptor { return request.interceptorContext.tracer; }; } -", - "src/interceptors/try-catch.ts": "import { - ChainedRequestInput, - OperationResponse, -} from '..'; +", + "src/interceptors/try-catch.ts": "import { + ChainedRequestInput, + OperationResponse, +} from '..'; + +/** + * Create an interceptor which returns the given error response and status should an error occur + * @param statusCode the status code to return when an error is thrown + * @param errorResponseBody the body to return when an error occurs + */ +export const buildTryCatchInterceptor = ( + statusCode: TStatus, + errorResponseBody: ErrorResponseBody, +) => async < + RequestParameters, + RequestBody, + Response extends OperationResponse, +>( + request: ChainedRequestInput< + RequestParameters, + RequestBody, + Response + >, +): Promise> => { + try { + return await request.chain.next(request); + } catch (e: any) { + // If the error looks like a response, return it as the response + if ('statusCode' in e) { + return e; + } + + // Log the error if the logger is present + if (request.interceptorContext.logger && request.interceptorContext.logger.error) { + request.interceptorContext.logger.error('Interceptor caught exception', e as Error); + } else { + console.error('Interceptor caught exception', e); + } + + // Return the default error message + return { statusCode, body: errorResponseBody }; + } +}; + +/** + * Interceptor for catching unhandled exceptions and returning a 500 error. + * Uncaught exceptions which look like OperationResponses will be returned, such that deeply nested code may return error + * responses, eg: \`throw ApiResponse.notFound({ message: 'Not found!' })\` + */ +export const tryCatchInterceptor = buildTryCatchInterceptor(500, { message: 'Internal Error' }); +", + "src/models/AdditionalPropertiesResponse.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; +import type { Dictionary } from './Dictionary'; +import { + DictionaryFromJSON, + DictionaryFromJSONTyped, + DictionaryToJSON, + instanceOfDictionary, +} from './Dictionary'; + +/** + * + * @export + * @interface AdditionalPropertiesResponse + */ +export interface AdditionalPropertiesResponse { + /** + * + * @type {Dictionary} + * @memberof AdditionalPropertiesResponse + */ + dictionaryOfObjects?: Dictionary; + /** + * + * @type {{ [key: string]: string; }} + * @memberof AdditionalPropertiesResponse + */ + dictionaryOfPrimitives?: { [key: string]: string; }; +} + + +/** + * Check if a given object implements the AdditionalPropertiesResponse interface. + */ +export function instanceOfAdditionalPropertiesResponse(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function AdditionalPropertiesResponseFromJSON(json: any): AdditionalPropertiesResponse { + return AdditionalPropertiesResponseFromJSONTyped(json, false); +} + +export function AdditionalPropertiesResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): AdditionalPropertiesResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'dictionaryOfObjects': !exists(json, 'dictionaryOfObjects') ? undefined : DictionaryFromJSON(json['dictionaryOfObjects']), + 'dictionaryOfPrimitives': !exists(json, 'dictionaryOfPrimitives') ? undefined : json['dictionaryOfPrimitives'], + }; +} + +export function AdditionalPropertiesResponseToJSON(value?: AdditionalPropertiesResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'dictionaryOfObjects': DictionaryToJSON(value.dictionaryOfObjects), + 'dictionaryOfPrimitives': value.dictionaryOfPrimitives, + }; +} + +", + "src/models/AnotherNamedOneOf.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; + +/** + * + * @export + * @interface AnotherNamedOneOf + */ +export interface AnotherNamedOneOf { + /** + * + * @type {string} + * @memberof AnotherNamedOneOf + */ + bar?: string; +} + + +/** + * Check if a given object implements the AnotherNamedOneOf interface. + */ +export function instanceOfAnotherNamedOneOf(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function AnotherNamedOneOfFromJSON(json: any): AnotherNamedOneOf { + return AnotherNamedOneOfFromJSONTyped(json, false); +} + +export function AnotherNamedOneOfFromJSONTyped(json: any, ignoreDiscriminator: boolean): AnotherNamedOneOf { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'bar': !exists(json, 'bar') ? undefined : json['bar'], + }; +} + +export function AnotherNamedOneOfToJSON(value?: AnotherNamedOneOf | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'bar': value.bar, + }; +} + +", + "src/models/ArrayOfOneOfs.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; +import type { NamedOneOfUnion } from './NamedOneOfUnion'; +import { + NamedOneOfUnionFromJSON, + NamedOneOfUnionFromJSONTyped, + NamedOneOfUnionToJSON, + instanceOfNamedOneOfUnion, +} from './NamedOneOfUnion'; + +/** + * + * @export + * @interface ArrayOfOneOfs + */ +export interface ArrayOfOneOfs { + /** + * + * @type {Array} + * @memberof ArrayOfOneOfs + */ + oneOfs?: Array; +} + /** - * Create an interceptor which returns the given error response and status should an error occur - * @param statusCode the status code to return when an error is thrown - * @param errorResponseBody the body to return when an error occurs + * Check if a given object implements the ArrayOfOneOfs interface. */ -export const buildTryCatchInterceptor = ( - statusCode: TStatus, - errorResponseBody: ErrorResponseBody, -) => async < - RequestParameters, - RequestBody, - Response extends OperationResponse, ->( - request: ChainedRequestInput< - RequestParameters, - RequestBody, - Response - >, -): Promise> => { - try { - return await request.chain.next(request); - } catch (e: any) { - // If the error looks like a response, return it as the response - if ('statusCode' in e) { - return e; +export function instanceOfArrayOfOneOfs(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function ArrayOfOneOfsFromJSON(json: any): ArrayOfOneOfs { + return ArrayOfOneOfsFromJSONTyped(json, false); +} + +export function ArrayOfOneOfsFromJSONTyped(json: any, ignoreDiscriminator: boolean): ArrayOfOneOfs { + if ((json === undefined) || (json === null)) { + return json; } + return { - // Log the error if the logger is present - if (request.interceptorContext.logger && request.interceptorContext.logger.error) { - request.interceptorContext.logger.error('Interceptor caught exception', e as Error); - } else { - console.error('Interceptor caught exception', e); + 'oneOfs': !exists(json, 'oneOfs') ? undefined : ((json['oneOfs'] as Array).map(NamedOneOfUnionFromJSON)), + }; +} + +export function ArrayOfOneOfsToJSON(value?: ArrayOfOneOfs | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; } + return { - // Return the default error message - return { statusCode, body: errorResponseBody }; - } -}; + 'oneOfs': value.oneOfs === undefined ? undefined : ((value.oneOfs as Array).map(NamedOneOfUnionToJSON)), + }; +} +", + "src/models/Dictionary.ts": "/* tslint:disable */ +/* eslint-disable */ /** - * Interceptor for catching unhandled exceptions and returning a 500 error. - * Uncaught exceptions which look like OperationResponses will be returned, such that deeply nested code may return error - * responses, eg: \`throw ApiResponse.notFound({ message: 'Not found!' })\` + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. */ -export const tryCatchInterceptor = buildTryCatchInterceptor(500, { message: 'Internal Error' }); +import { exists, mapValues } from './model-utils'; +import type { SomeObject } from './SomeObject'; +import { + SomeObjectFromJSON, + SomeObjectFromJSONTyped, + SomeObjectToJSON, + instanceOfSomeObject, +} from './SomeObject'; + +/** + * + * @export + * @interface Dictionary + */ +export interface Dictionary { + [key: string]: Array; +} + + +/** + * Check if a given object implements the Dictionary interface. + */ +export function instanceOfDictionary(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DictionaryFromJSON(json: any): Dictionary { + return DictionaryFromJSONTyped(json, false); +} + +export function DictionaryFromJSONTyped(json: any, ignoreDiscriminator: boolean): Dictionary { + return json; +} + +export function DictionaryToJSON(value?: Dictionary | null): any { + return value; +} + ", "src/models/InlineEnum200Response.ts": "/* tslint:disable */ /* eslint-disable */ @@ -9736,13 +10480,221 @@ export function MyEnumToJSON(value?: MyEnum | null): any { return value; } +", + "src/models/NamedOneOf.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; + +/** + * + * @export + * @interface NamedOneOf + */ +export interface NamedOneOf { + /** + * + * @type {string} + * @memberof NamedOneOf + */ + foo?: string; +} + + +/** + * Check if a given object implements the NamedOneOf interface. + */ +export function instanceOfNamedOneOf(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function NamedOneOfFromJSON(json: any): NamedOneOf { + return NamedOneOfFromJSONTyped(json, false); +} + +export function NamedOneOfFromJSONTyped(json: any, ignoreDiscriminator: boolean): NamedOneOf { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'foo': !exists(json, 'foo') ? undefined : json['foo'], + }; +} + +export function NamedOneOfToJSON(value?: NamedOneOf | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'foo': value.foo, + }; +} + +", + "src/models/NamedOneOfUnion.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; +import type { AnotherNamedOneOf } from './AnotherNamedOneOf'; +import { + AnotherNamedOneOfFromJSON, + AnotherNamedOneOfFromJSONTyped, + AnotherNamedOneOfToJSON, + instanceOfAnotherNamedOneOf, +} from './AnotherNamedOneOf'; +import type { NamedOneOf } from './NamedOneOf'; +import { + NamedOneOfFromJSON, + NamedOneOfFromJSONTyped, + NamedOneOfToJSON, + instanceOfNamedOneOf, +} from './NamedOneOf'; + +/** + * @type NamedOneOfUnion + * + * @export + */ +export type NamedOneOfUnion = NamedOneOf | AnotherNamedOneOf; + + +/** + * Check if a given object implements the NamedOneOfUnion interface. + */ +export function instanceOfNamedOneOfUnion(value: object): boolean { + return instanceOfNamedOneOf(value) || instanceOfAnotherNamedOneOf(value) +} + +export function NamedOneOfUnionFromJSON(json: any): NamedOneOfUnion { + return NamedOneOfUnionFromJSONTyped(json, false); +} + +export function NamedOneOfUnionFromJSONTyped(json: any, ignoreDiscriminator: boolean): NamedOneOfUnion { + if ((json === undefined) || (json === null)) { + return json; + } + return { + ...NamedOneOfFromJSONTyped(json, true), + ...AnotherNamedOneOfFromJSONTyped(json, true), + }; +} + +export function NamedOneOfUnionToJSON(value?: NamedOneOfUnion | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + ...NamedOneOfToJSON(value as any), + ...AnotherNamedOneOfToJSON(value as any), + }; +} + +", + "src/models/SomeObject.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; + +/** + * + * @export + * @interface SomeObject + */ +export interface SomeObject { + /** + * + * @type {string} + * @memberof SomeObject + */ + a?: string; +} + + +/** + * Check if a given object implements the SomeObject interface. + */ +export function instanceOfSomeObject(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function SomeObjectFromJSON(json: any): SomeObject { + return SomeObjectFromJSONTyped(json, false); +} + +export function SomeObjectFromJSONTyped(json: any, ignoreDiscriminator: boolean): SomeObject { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'a': !exists(json, 'a') ? undefined : json['a'], + }; +} + +export function SomeObjectToJSON(value?: SomeObject | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'a': value.a, + }; +} + ", "src/models/index.ts": "/* tslint:disable */ /* eslint-disable */ +export * from './AdditionalPropertiesResponse'; +export * from './AnotherNamedOneOf'; +export * from './ArrayOfOneOfs'; +export * from './Dictionary'; export * from './InlineEnum200Response'; export * from './InlineEnum200ResponseCategoryEnum'; export * from './InlineRequestBodyRequestContent'; export * from './MyEnum'; +export * from './NamedOneOf'; +export * from './NamedOneOfUnion'; +export * from './SomeObject'; ", "src/models/model-utils.ts": "/* tslint:disable */ /* eslint-disable */