From 4fb92b5ff85d000856f2faacfaf58d062d46cba9 Mon Sep 17 00:00:00 2001 From: Jack Stevenson Date: Mon, 14 Oct 2024 12:44:13 +1100 Subject: [PATCH] fix(type-safe-api): more robust support for composed schemas in typescript (#856) Revamped models generated from composed schemas (ie oneOf, anyOf, allOf). Rather than inlining properties, use intersection and union types to represent allOf and anyOf. oneOf is difficult to model in typescript, so we opt for the same behaviour as anyOf for now. OpenAPI generator never worked for anyOf/oneOf with a mixture of object and primitive types, whereas this change generates valid code for this case. --- .../docs/templates/markdown/model.ejs | 2 +- .../docs/templates/plantuml/schemas.ejs | 4 +- .../type-safe-api/generators/generate-next.ts | 125 +- .../templates/client/models/models.ejs | 65 +- .../resources/specs/composite-models.yaml | 145 + .../test/resources/specs/data-types.yaml | 17 +- .../generate-mock-data.test.ts.snap | 9 + .../__snapshots__/java.test.ts.snap | 14764 ++++++++++++++-- .../__snapshots__/python.test.ts.snap | 6499 ++++++- .../typescript-react-query-hooks.test.ts.snap | 7 +- .../__snapshots__/typescript.test.ts.snap | 4384 ++++- .../typescript-websocket-client.test.ts.snap | 8 +- .../__snapshots__/typescript.test.ts.snap | 8 +- .../test/scripts/generators/java.test.ts | 1 + .../test/scripts/generators/python.test.ts | 1 + .../scripts/generators/typescript.test.ts | 1 + 16 files changed, 24381 insertions(+), 1659 deletions(-) create mode 100644 packages/type-safe-api/test/resources/specs/composite-models.yaml diff --git a/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/markdown/model.ejs b/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/markdown/model.ejs index a4f535151..2b5fcf69c 100644 --- a/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/markdown/model.ejs +++ b/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/markdown/model.ejs @@ -12,7 +12,7 @@ | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -<%_ model.resolvedProperties.forEach(property => { _%> +<%_ model.properties.forEach(property => { _%> | **<%- property.name %>** | <% if (property.isPrimitive || property.export === "array" || property.export === "dictionary") { %>**<%- property.javaType %>**<% } else { %>[**<%- property.type %>**](<%- property.type %>.md)<% } %> | <%- property.description || '' %> | <% if (!property.isRequired) { %>[optional] <% } %><% if (property.isReadOnly) { %>[readonly] <% } %><% if (property.defaultValue) { %>[default to <%- property.defaultValue %>]<% } %> | <%_ }); _%> diff --git a/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/plantuml/schemas.ejs b/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/plantuml/schemas.ejs index 3bb88ee15..3d935702b 100644 --- a/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/plantuml/schemas.ejs +++ b/packages/type-safe-api/scripts/type-safe-api/generators/docs/templates/plantuml/schemas.ejs @@ -12,7 +12,7 @@ title <%- info.title %> Schemas Diagram <%_ models.forEach((model) => { _%> entity <%- model.name %> { -<%_ model.resolvedProperties.forEach(property => { _%> +<%_ model.properties.forEach(property => { _%> <% if (property.isRequired) { %>* <% } %><%- property.name %>: <%- property.javaType %> <%_ }); _%> } @@ -20,7 +20,7 @@ entity <%- model.name %> { <%_ }); _%> <%_ models.forEach((model) => { _%> -<%_ model.resolvedProperties.forEach((property) => { _%> +<%_ model.properties.forEach((property) => { _%> <%_ if (!property.isPrimitive) { _%> <%- model.name %> -- <% if (["array", "dictionary"].includes(property.export)) { %>"0..*" <% } %><%- property.type %> : <%- property.name %> <%_ } _%> 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 84f202789..ec816b5a8 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 @@ -201,23 +201,39 @@ const splitAndWriteFiles = (renderedFileContents: string[], outputPath: string) const COMPOSED_SCHEMA_TYPES = new Set(["one-of", "any-of", "all-of"]); const PRIMITIVE_TYPES = new Set(["string", "integer", "number", "boolean", "null", "any", "binary", "void"]); -const resolveComposedProperties = (data: parseOpenapi.ParsedSpecification, model: parseOpenapi.Model): parseOpenapi.Model[] => { - if (COMPOSED_SCHEMA_TYPES.has(model.export)) { - // Find the composed model, if any - const parentModelProperty = model.properties.find(p => !p.name && p.export === "reference"); - const composedModel = data.models.find(m => m.name === parentModelProperty?.type); - - // The actual properties for a composed model are nested under a special property called "properties" - return [ - ...(model.properties.find(p => p.name === "properties")?.properties ?? []), - ...(composedModel ? resolveComposedProperties(data, composedModel).map((p => { - (p as any)._composedFrom = composedModel.name; - return p; - })) : []), - ]; - } +/** + * Mutates the given data to ensure composite models (ie allOf, oneOf, anyOf) have the necessary + * properties for representing them in generated code. Adds `composedModels` and `composedPrimitives` + * which contain the models and primitive types that each model is composed of. + */ +const ensureCompositeModels = (data: parseOpenapi.ParsedSpecification) => { + const visited = new Set(); + data.models.forEach(model => mutateModelWithCompositeProperties(data, model, visited)); +} - return model.properties ?? []; +const mutateModelWithCompositeProperties = (data: parseOpenapi.ParsedSpecification, model: parseOpenapi.Model, visited: Set) => { + if (COMPOSED_SCHEMA_TYPES.has(model.export) && !visited.has(model)) { + visited.add(model); + + // Find the models/primitives which this is composed from + const composedModelReferences = model.properties.filter(p => !p.name && p.export === "reference"); + const composedPrimitives = model.properties.filter(p => !p.name && p.export !== "reference"); + + const modelsByName = Object.fromEntries(data.models.map(m => [m.name, m])); + const composedModels = composedModelReferences.flatMap(r => modelsByName[r.type] ? [modelsByName[r.type]] : []); + // Recursively resolve composed properties of properties, to ensure mixins for all-of include all recursive all-of properties + composedModels.forEach(m => mutateModelWithCompositeProperties(data, m, visited)); + + // For all-of models, we include all composed model properties. + if (model.export === "all-of") { + if (composedPrimitives.length > 0) { + throw new Error(`Schema "${model.name}" defines allOf with non-object types. allOf may only compose object types in the OpenAPI specification.`); + } + } + + (model as any).composedModels = composedModels; + (model as any).composedPrimitives = composedPrimitives; + } }; const toTypescriptPrimitive = (property: parseOpenapi.Model): string => { @@ -340,24 +356,26 @@ const toPythonType = (property: parseOpenapi.Model): string => { * Mutates the given model to add language specific types and names */ const mutateModelWithAdditionalTypes = (model: parseOpenapi.Model) => { + // Trim any surrounding quotes from name + model.name = _trim(model.name, `"'`); + (model as any).typescriptName = model.name; (model as any).typescriptType = toTypeScriptType(model); + (model as any).javaName = model.name; (model as any).javaType = toJavaType(model); + (model as any).pythonName = _snakeCase(model.name); (model as any).pythonType = toPythonType(model); (model as any).isPrimitive = PRIMITIVE_TYPES.has(model.type); - - // Trim any surrounding quotes from name - model.name = _trim(model.name, `"'`); }; const mutateWithOpenapiSchemaProperties = (spec: OpenAPIV3.Document, model: parseOpenapi.Model, schema: OpenAPIV3.SchemaObject, visited: Set = new Set()) => { (model as any).format = schema.format; - (model as any).oapiType = schema.type; (model as any).isInteger = schema.type === "integer"; (model as any).isShort = schema.format === "int32"; (model as any).isLong = schema.format === "int64"; (model as any).deprecated = !!schema.deprecated; (model as any).openapiType = schema.type; + (model as any).isNotSchema = !!schema.not; visited.add(model); @@ -366,6 +384,19 @@ const mutateWithOpenapiSchemaProperties = (spec: OpenAPIV3.Document, model: pars const subSchema = resolveIfRef(spec, schema.items); mutateWithOpenapiSchemaProperties(spec, model.link, subSchema, visited); } + + // Also apply to object properties recursively + if (model.export === "dictionary" && model.link && 'additionalProperties' in schema && schema.additionalProperties && !visited.has(model.link)) { + const subSchema = resolveIfRef(spec, schema.additionalProperties); + // Additional properties can be "true" rather than a type + if (subSchema !== true) { + mutateWithOpenapiSchemaProperties(spec, model.link, subSchema, visited); + } + } + model.properties.filter(p => !visited.has(p) && schema.properties?.[p.name]).forEach(property => { + const subSchema = resolveIfRef(spec, schema.properties![property.name]); + mutateWithOpenapiSchemaProperties(spec, property, subSchema, visited); + }); }; interface SubSchema { @@ -380,25 +411,41 @@ interface SubSchemaRef { readonly schema: OpenAPIV3.SchemaObject; } -const isInlineObjectOrArraySubSchema = (schema?: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject): schema is OpenAPIV3.SchemaObject => !!schema && !isRef(schema) && ["object", "array"].includes(schema.type as any); +const isCompositeSchema = (schema: OpenAPIV3.SchemaObject) => + !!schema.allOf || !!schema.anyOf || !!schema.oneOf; + +const hasSubSchemasToVisit = (schema?: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject): schema is OpenAPIV3.SchemaObject => + !!schema && !isRef(schema) && (["object", "array"].includes(schema.type as any) || isCompositeSchema(schema) || !!schema.not); + +const filterInlineCompositeSchemas = (schemas: (OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject)[], nameParts: string[], namePartPrefix: string, prop: string): SubSchema[] => { + 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}]` }; + inlineSchemaIndex++; + return [subSchema]; + } + return []; + }); +} const hoistInlineObjectSubSchemas = (nameParts: string[], schema: OpenAPIV3.SchemaObject): SubSchemaRef[] => { - // Find all the inline subschemas + // Find all the inline subschemas we should visit const inlineSubSchemas: SubSchema[] = [ - ...(isInlineObjectOrArraySubSchema(schema.not) ? [{ nameParts: [...nameParts, 'Not'], schema: schema.not, prop: 'not' }] : []), - ...(schema.anyOf ? schema.anyOf.filter(isInlineObjectOrArraySubSchema).map((s, i) => ({ nameParts: [...nameParts, `${i}`], schema: s, prop: `anyOf.[${i}]` })) : []), - ...(schema.allOf ? schema.allOf.filter(isInlineObjectOrArraySubSchema).map((s, i) => ({ nameParts: [...nameParts, `${i}`], schema: s, prop: `allOf.[${i}]` })) : []), - ...(schema.oneOf ? schema.oneOf.filter(isInlineObjectOrArraySubSchema).map((s, i) => ({ nameParts: [...nameParts, `${i}`], schema: s, prop: `oneOf.[${i}]` })) : []), - ...('items' in schema && isInlineObjectOrArraySubSchema(schema.items) ? [{ nameParts: [...nameParts, 'Inner'], schema: schema.items, prop: 'items' }] : []), - ...(Object.entries(schema.properties ?? {}).filter(([, s]) => isInlineObjectOrArraySubSchema(s)).map(([name, s]) => ({ nameParts: [...nameParts, name], schema: s as OpenAPIV3.SchemaObject, prop: `properties.${name}` }))), - ...((typeof schema.additionalProperties !== "boolean" && isInlineObjectOrArraySubSchema(schema.additionalProperties)) ? [{ nameParts: [...nameParts, 'Value'], schema: schema.additionalProperties, prop: `additionalProperties` }] : []), + ...(hasSubSchemasToVisit(schema.not) ? [{ nameParts: [...nameParts, 'Not'], schema: schema.not, prop: 'not' }] : []), + ...(schema.anyOf ? filterInlineCompositeSchemas(schema.anyOf, nameParts, 'AnyOf', 'anyOf') : []), + ...(schema.allOf ? filterInlineCompositeSchemas(schema.allOf, nameParts, 'AllOf', 'allOf') : []), + ...(schema.oneOf ? filterInlineCompositeSchemas(schema.oneOf, nameParts, 'OneOf', 'oneOf') : []), + ...('items' in schema && hasSubSchemasToVisit(schema.items) ? [{ nameParts: [...nameParts, 'Inner'], schema: schema.items, prop: 'items' }] : []), + ...(Object.entries(schema.properties ?? {}).filter(([, s]) => hasSubSchemasToVisit(s)).map(([name, s]) => ({ nameParts: [...nameParts, name], schema: s as OpenAPIV3.SchemaObject, prop: `properties.${name}` }))), + ...((typeof schema.additionalProperties !== "boolean" && hasSubSchemasToVisit(schema.additionalProperties)) ? [{ nameParts: [...nameParts, 'Value'], schema: schema.additionalProperties, prop: `additionalProperties` }] : []), ]; // Hoist these recursively first (ie depth first search) so that we don't miss refs const recursiveRefs = inlineSubSchemas.flatMap((s) => hoistInlineObjectSubSchemas(s.nameParts, s.schema)); - // Clone the object subschemas to build the refs - const refs = inlineSubSchemas.filter(s => s.schema.type === "object" && ["items", "additionalProperties"].includes(s.prop)).map(s => { + // Clone the object subschemas to build the refs. Note that only objects with "properties" are hoisted as these are non-dictionary types + const refs = inlineSubSchemas.filter(s => (s.schema.type === "object" && s.schema.properties) || isCompositeSchema(s.schema)).map(s => { const name = s.nameParts.map(_upperFirst).join(''); const $ref = `#/components/schemas/${name}`; const ref = { @@ -472,6 +519,9 @@ const buildData = (inSpec: OpenAPIV3.Document, metadata: any) => { // Start with the data from https://github.com/webpro/parse-openapi which extracts most of what we need const data = { ...parseOpenapi.parse(spec), metadata }; + // Mutate the models with enough data to render composite models in the templates + ensureCompositeModels(data); + // Augment operations with additional data data.services.forEach((service) => { @@ -614,20 +664,19 @@ const buildData = (inSpec: OpenAPIV3.Document, metadata: any) => { // Augment models with additional data data.models.forEach((model) => { + // Add a snake_case name + (model as any).nameSnakeCase = _snakeCase(model.name); + const matchingSpecModel = spec?.components?.schemas?.[model.name] if (matchingSpecModel) { const specModel = isRef(matchingSpecModel) ? resolveRef(spec, matchingSpecModel.$ref) as OpenAPIV3.SchemaObject : matchingSpecModel; - // Resolve properties inherited from composed schemas - const composedProperties = resolveComposedProperties(data, model); - (model as any).resolvedProperties = composedProperties; - // Add unique imports (model as any).uniqueImports = _orderBy(_uniq([ ...model.imports, - // Include composed property imports, if any - ...composedProperties.filter(p => p.export === "reference").map(p => p.type), + // Include property imports, if any + ...model.properties.filter(p => p.export === "reference").map(p => p.type), ])); // Add deprecated flag if present @@ -639,7 +688,7 @@ const buildData = (inSpec: OpenAPIV3.Document, metadata: any) => { } // Augment properties with additional data - [...model.properties, ...((model as any).resolvedProperties as parseOpenapi.Model[])].forEach((property) => { + model.properties.forEach((property) => { const matchingSpecProperty = specModel.properties?.[property.name]; if (matchingSpecProperty) { 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 ce14d8875..78d5c434e 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 @@ -20,14 +20,19 @@ * Do not edit the class manually. */ import { exists, mapValues } from './model-utils'; +<%_ const modelsByName = Object.fromEntries(models.map(m => [m.name, m])); _%> <%_ model.uniqueImports.forEach((importName) => { _%> import type { <%= importName %> } from './<%= importName %>'; import { <%= importName %>FromJSON, <%= importName %>FromJSONTyped, <%= importName %>ToJSON, + <%_ if (!(modelsByName[importName] && modelsByName[importName].export === "enum")) { _%> + instanceOf<%= importName %>, + <%_ } _%> } from './<%= importName %>'; <%_ }); _%> +<%_ const isComposite = model.export === "one-of" || model.export === "any-of" || model.export === "all-of"; _%> <%_ if (model.export === "enum") { _%> /** @@ -40,6 +45,13 @@ export type <%= model.name %> = <%- enumMember.value %><% if (i < model.enum.length - 1) { %> | <% } %> <%_ }); _%> +<%_ } else if (isComposite) { _%> +/** + * @type <%= model.name %> + * <%- model.description || '' %> + * @export + */ +export type <%- model.name %> =<% model.properties.forEach((composedType, i) => { %><% if (i > 0) { %><% if (model.export === "all-of") { %> &<% } else { %> |<% } %><% } %> <%- composedType.typescriptType %><% }); %>; <%_ } else { _%> /** * <%- model.description || '' %> @@ -53,7 +65,7 @@ export interface <%= model.name %> { <%_ if (model.additionalProperties) { _%> [key: string]: <%- model.additionalProperties.typescriptType %>; <%_ } _%> -<%_ model.resolvedProperties.forEach((property) => { _%> +<%_ model.properties.forEach((property) => { _%> /** * <%- property.description || '' %> * @type {<%- property.typescriptType %>} @@ -65,20 +77,25 @@ export interface <%= model.name %> { <%= property.isReadOnly ? 'readonly ' : '' %><%= property.typescriptName %><%= property.isRequired ? '' : '?' %>: <%- property.typescriptType %><%= (property.isNullable || property.type === "any") ? ' | null' : '' %>; <%_ }); _%> } +<%_ } _%> +<%_ if (model.export !== "enum") { _%> /** * Check if a given object implements the <%= model.name %> interface. */ export function instanceOf<%= model.name %>(value: object): boolean { +<%_ if (isComposite) { _%> + return <% model.properties.forEach((property, i) => { %><% if (i > 0) { %> <% if (model.export === "all-of") { %>&&<% } else { %>||<% } %> <% } %><% if (property.isPrimitive) { %>typeof value === "<%- property.typescriptType %>"<% } else { %>instanceOf<%- property.type %>(value)<% } %><% }); %> +<%_ } else { _%> let isInstance = true; -<%_ model.resolvedProperties.forEach((property) => { _%> +<%_ model.properties.forEach((property) => { _%> <%_ if (property.isRequired) { _%> isInstance = isInstance && "<%= property.name %>" in value; <%_ } _%> <%_ }); _%> - return isInstance; +<%_ } _%> } <%_ } _%> @@ -87,16 +104,32 @@ export function <%= model.name %>FromJSON(json: any): <%= model.name %> { } export function <%= model.name %>FromJSONTyped(json: any, ignoreDiscriminator: boolean): <%= model.name %> { -<%_ if (model.resolvedProperties.length > 0) { _%> +<%_ if (model.properties.length > 0) { _%> if ((json === undefined) || (json === null)) { return json; } +<%_ if (isComposite) { _%> +<%_ model.composedPrimitives.forEach((primitive) => { _%> + if (typeof json === "<%- primitive.typescriptType %>") { + return json; + } +<%_ }); _%> +<%_ if (model.composedModels.length > 0) { _%> + return { + <%_ model.properties.filter(p => !p.isPrimitive).forEach((composedType) => { _%> + ...<%- composedType.typescriptType %>FromJSONTyped(json, true), + <%_ }); _%> + }; +<%_ } else { _%> + return json; +<%_ } _%> +<%_ } else { _%> return { <%_ if (model.additionalProperties) { _%> ...json, <%_ } _%> -<%_ model.resolvedProperties.forEach((property) => { _%> +<%_ model.properties.forEach((property) => { _%> <%_ if (property.isPrimitive) { _%> '<%= property.typescriptName %>': <% if (!property.isRequired) { %>!exists(json, '<%- property.name %>') ? undefined : <% } %><% if (["date", "date-time"].includes(property.format) && property.isNullable) { %>json['<%- property.name %>'] === null ? null : <% } %><% if (["date", "date-time"].includes(property.format)) { %>(new Date(json['<%= property.name %>']))<% } else { %>json['<%= property.name %>']<% } %>, <%_ } else if (property.export === 'array') { _%> @@ -108,25 +141,42 @@ export function <%= model.name %>FromJSONTyped(json: any, ignoreDiscriminator: b <%_ } _%> <%_ }); _%> }; +<%_ } _%> <%_ } else { _%> return json; <%_ } _%> } export function <%= model.name %>ToJSON(value?: <%= model.name %> | null): any { -<%_ if (model.resolvedProperties.length > 0) { _%> +<%_ if (model.properties.length > 0) { _%> if (value === undefined) { return undefined; } if (value === null) { return null; } +<%_ if (isComposite) { _%> + <%_ model.composedPrimitives.forEach((primitive) => { _%> + if (typeof value === "<%- primitive.typescriptType %>") { + return value; + } + <%_ }); _%> + <%_ if (model.composedModels.length > 0) { _%> + return { + <%_ model.properties.filter(p => !p.isPrimitive).forEach((property, i) => { _%> + ...<%- property.typescriptType %>ToJSON(value as any), + <%_ }); _%> + }; + <%_ } else { _%> + return value; + <%_ } _%> +<%_ } else { _%> return { <%_ if (model.additionalProperties) { _%> ...value, <%_ } _%> -<%_ model.resolvedProperties.forEach((property) => { _%> +<%_ model.properties.forEach((property) => { _%> <%_ if (!property.isReadOnly) { _%> <%_ if (property.isPrimitive && ["date", "date-time"].includes(property.format)) { _%> '<%= property.name %>': <% if (!property.isRequired) { %>value.<%- property.typescriptName %> === undefined ? undefined : <% } %>(<% if (property.isNullable) { %>value.<%- property.typescriptName %> === null ? null : <% } %>value.<%- property.typescriptName %>.toISOString()<% if (property.format === 'date') { %>.substr(0,10)<% } %>), @@ -144,6 +194,7 @@ export function <%= model.name %>ToJSON(value?: <%= model.name %> | null): any { <%_ } _%> <%_ }); _%> }; +<%_ } _%> <%_ } else { _%> return value; <%_ } _%> diff --git a/packages/type-safe-api/test/resources/specs/composite-models.yaml b/packages/type-safe-api/test/resources/specs/composite-models.yaml new file mode 100644 index 000000000..47eb99cad --- /dev/null +++ b/packages/type-safe-api/test/resources/specs/composite-models.yaml @@ -0,0 +1,145 @@ +openapi: 3.0.3 +info: + version: 1.0.0 + title: composite models +paths: + /op: + get: + responses: + 200: + description: Successful response + content: + 'application/json': + schema: + $ref: '#/components/schemas/Wrapper' +components: + schemas: + A: + type: object + required: + - a + properties: + a: + type: string + B: + type: object + required: + - b + properties: + b: + type: string + C: + type: object + required: + - c + properties: + c: + type: string + AllOfInlineAndRefs: + allOf: + - type: object + required: + - d + properties: + d: + type: string + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + - type: object + properties: + e: + type: string + AllOfRefs: + allOf: + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + AnyOfPrimitives: + anyOf: + - type: string + - type: integer + AnyOfPrimitivesAndRefs: + anyOf: + - type: string + - $ref: '#/components/schemas/A' + AnyOfRefs: + anyOf: + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + AnyOfInlineAndRefs: + anyOf: + - type: object + required: + - d + properties: + d: + type: string + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + - type: object + properties: + e: + type: string + OneOfPrimitives: + oneOf: + - type: string + - type: integer + OneOfPrimitivesAndRefs: + oneOf: + - type: string + - $ref: '#/components/schemas/A' + OneOfRefs: + oneOf: + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + OneOfInlineAndRefs: + oneOf: + - type: object + required: + - d + properties: + d: + type: string + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + - type: object + properties: + e: + type: string + Wrapper: + type: object + properties: + allOf: + type: object + properties: + refs: + $ref: '#/components/schemas/AllOfRefs' + inlineAndRefs: + $ref: '#/components/schemas/AllOfInlineAndRefs' + anyOf: + type: object + properties: + refs: + $ref: '#/components/schemas/AnyOfRefs' + inlineAndRefs: + $ref: '#/components/schemas/AnyOfInlineAndRefs' + primitives: + $ref: '#/components/schemas/AnyOfPrimitives' + primitivesAndRefs: + $ref: '#/components/schemas/AnyOfPrimitivesAndRefs' + oneOf: + type: object + properties: + refs: + $ref: '#/components/schemas/OneOfRefs' + inlineAndRefs: + $ref: '#/components/schemas/OneOfInlineAndRefs' + primitives: + $ref: '#/components/schemas/OneOfPrimitives' + primitivesAndRefs: + $ref: '#/components/schemas/OneOfPrimitivesAndRefs' diff --git a/packages/type-safe-api/test/resources/specs/data-types.yaml b/packages/type-safe-api/test/resources/specs/data-types.yaml index aef66d66c..c5fabfab9 100644 --- a/packages/type-safe-api/test/resources/specs/data-types.yaml +++ b/packages/type-safe-api/test/resources/specs/data-types.yaml @@ -99,4 +99,19 @@ paths: items: type: integer minimum: 10 - maximum: 20 \ No newline at end of file + maximum: 20 + myObject: + type: object + properties: + one: + type: object + properties: + twoString: + type: string + two: + type: object + properties: + threeString: + type: string + oneString: + type: string \ No newline at end of file diff --git a/packages/type-safe-api/test/scripts/custom/mock-data/__snapshots__/generate-mock-data.test.ts.snap b/packages/type-safe-api/test/scripts/custom/mock-data/__snapshots__/generate-mock-data.test.ts.snap index 63c33a7fc..866661ac9 100644 --- a/packages/type-safe-api/test/scripts/custom/mock-data/__snapshots__/generate-mock-data.test.ts.snap +++ b/packages/type-safe-api/test/scripts/custom/mock-data/__snapshots__/generate-mock-data.test.ts.snap @@ -69,6 +69,15 @@ exports[`Generate Mock Data Unit Tests Generates Mock Data For Many Data Types 1 "myNot": "quidem advoco utpote", "myNotString": {}, "myNumber": 0.5658850050531328, + "myObject": { + "one": { + "two": { + "threeString": "sum vindico taedium", + }, + "twoString": "esse succedo caput", + }, + "oneString": "dens excepturi vero", + }, "myOneOf": "victus sto agnosco", "myRegexPattern": "5555-pattern-nnn", "myString": "laborum articulus benevolentia", 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 f44bebe5c..8f1fa7314 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 @@ -6189,7 +6189,7 @@ public class TemplateBody { } `; -exports[`Java Client Code Generation Script Unit Tests Generates With data-types.yaml 1`] = ` +exports[`Java Client Code Generation Script Unit Tests Generates With composite-models.yaml 1`] = ` { ".github/workflows/maven.yml": "# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven @@ -6206,7 +6206,7 @@ on: jobs: build: - name: Build Data Types + name: Build composite models runs-on: ubuntu-latest strategy: matrix: @@ -6276,14 +6276,26 @@ README.md api/openapi.yaml build.gradle build.sbt -docs/DataTypes200Response.md -docs/DataTypes200ResponseMyAllOf.md -docs/DataTypes200ResponseMyAllOfAllOf.md -docs/DataTypes200ResponseMyAllOfAllOf1.md -docs/DataTypes200ResponseMyAnyOf.md -docs/DataTypes200ResponseMyNotNot.md -docs/DataTypes200ResponseMyOneOf.md +docs/A.md +docs/AllOfInlineAndRefs.md +docs/AllOfInlineAndRefsAllOf.md +docs/AllOfInlineAndRefsAllOf1.md +docs/AllOfRefs.md +docs/AnyOfInlineAndRefs.md +docs/AnyOfPrimitives.md +docs/AnyOfPrimitivesAndRefs.md +docs/AnyOfRefs.md +docs/B.md +docs/C.md docs/DefaultApi.md +docs/OneOfInlineAndRefs.md +docs/OneOfPrimitives.md +docs/OneOfPrimitivesAndRefs.md +docs/OneOfRefs.md +docs/Wrapper.md +docs/WrapperAllOf.md +docs/WrapperAnyOf.md +docs/WrapperOneOf.md git_push.sh gradle.properties gradle/wrapper/gradle-wrapper.jar @@ -6316,22 +6328,46 @@ src/main/java/test/test/runtime/auth/ApiKeyAuth.java src/main/java/test/test/runtime/auth/Authentication.java src/main/java/test/test/runtime/auth/HttpBasicAuth.java src/main/java/test/test/runtime/auth/HttpBearerAuth.java +src/main/java/test/test/runtime/model/A.java src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java -src/main/java/test/test/runtime/model/DataTypes200Response.java -src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOf.java -src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf.java -src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf1.java -src/main/java/test/test/runtime/model/DataTypes200ResponseMyAnyOf.java -src/main/java/test/test/runtime/model/DataTypes200ResponseMyNotNot.java -src/main/java/test/test/runtime/model/DataTypes200ResponseMyOneOf.java +src/main/java/test/test/runtime/model/AllOfInlineAndRefs.java +src/main/java/test/test/runtime/model/AllOfInlineAndRefsAllOf.java +src/main/java/test/test/runtime/model/AllOfInlineAndRefsAllOf1.java +src/main/java/test/test/runtime/model/AllOfRefs.java +src/main/java/test/test/runtime/model/AnyOfInlineAndRefs.java +src/main/java/test/test/runtime/model/AnyOfPrimitives.java +src/main/java/test/test/runtime/model/AnyOfPrimitivesAndRefs.java +src/main/java/test/test/runtime/model/AnyOfRefs.java +src/main/java/test/test/runtime/model/B.java +src/main/java/test/test/runtime/model/C.java +src/main/java/test/test/runtime/model/OneOfInlineAndRefs.java +src/main/java/test/test/runtime/model/OneOfPrimitives.java +src/main/java/test/test/runtime/model/OneOfPrimitivesAndRefs.java +src/main/java/test/test/runtime/model/OneOfRefs.java +src/main/java/test/test/runtime/model/Wrapper.java +src/main/java/test/test/runtime/model/WrapperAllOf.java +src/main/java/test/test/runtime/model/WrapperAnyOf.java +src/main/java/test/test/runtime/model/WrapperOneOf.java src/test/java/test/test/runtime/api/DefaultApiTest.java -src/test/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf1Test.java -src/test/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOfTest.java -src/test/java/test/test/runtime/model/DataTypes200ResponseMyAllOfTest.java -src/test/java/test/test/runtime/model/DataTypes200ResponseMyAnyOfTest.java -src/test/java/test/test/runtime/model/DataTypes200ResponseMyNotNotTest.java -src/test/java/test/test/runtime/model/DataTypes200ResponseMyOneOfTest.java -src/test/java/test/test/runtime/model/DataTypes200ResponseTest.java +src/test/java/test/test/runtime/model/ATest.java +src/test/java/test/test/runtime/model/AllOfInlineAndRefsAllOf1Test.java +src/test/java/test/test/runtime/model/AllOfInlineAndRefsAllOfTest.java +src/test/java/test/test/runtime/model/AllOfInlineAndRefsTest.java +src/test/java/test/test/runtime/model/AllOfRefsTest.java +src/test/java/test/test/runtime/model/AnyOfInlineAndRefsTest.java +src/test/java/test/test/runtime/model/AnyOfPrimitivesAndRefsTest.java +src/test/java/test/test/runtime/model/AnyOfPrimitivesTest.java +src/test/java/test/test/runtime/model/AnyOfRefsTest.java +src/test/java/test/test/runtime/model/BTest.java +src/test/java/test/test/runtime/model/CTest.java +src/test/java/test/test/runtime/model/OneOfInlineAndRefsTest.java +src/test/java/test/test/runtime/model/OneOfPrimitivesAndRefsTest.java +src/test/java/test/test/runtime/model/OneOfPrimitivesTest.java +src/test/java/test/test/runtime/model/OneOfRefsTest.java +src/test/java/test/test/runtime/model/WrapperAllOfTest.java +src/test/java/test/test/runtime/model/WrapperAnyOfTest.java +src/test/java/test/test/runtime/model/WrapperOneOfTest.java +src/test/java/test/test/runtime/model/WrapperTest.java src/main/java/test/test/runtime/api/handlers/Handlers.java src/main/java/test/test/runtime/api/handlers/Response.java src/main/java/test/test/runtime/api/handlers/ApiResponse.java @@ -6342,12 +6378,12 @@ 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/data_types/DataTypesResponse.java -src/main/java/test/test/runtime/api/handlers/data_types/DataTypes200Response.java -src/main/java/test/test/runtime/api/handlers/data_types/DataTypesRequestParameters.java -src/main/java/test/test/runtime/api/handlers/data_types/DataTypesInput.java -src/main/java/test/test/runtime/api/handlers/data_types/DataTypesRequestInput.java -src/main/java/test/test/runtime/api/handlers/data_types/DataTypes.java +src/main/java/test/test/runtime/api/handlers/op_get/OpGetResponse.java +src/main/java/test/test/runtime/api/handlers/op_get/OpGet200Response.java +src/main/java/test/test/runtime/api/handlers/op_get/OpGetRequestParameters.java +src/main/java/test/test/runtime/api/handlers/op_get/OpGetInput.java +src/main/java/test/test/runtime/api/handlers/op_get/OpGetRequestInput.java +src/main/java/test/test/runtime/api/handlers/op_get/OpGet.java src/main/java/test/test/runtime/api/handlers/HandlerRouter.java src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java src/main/java/test/test/runtime/api/interceptors/ResponseHeadersInterceptor.java @@ -6368,7 +6404,7 @@ src/main/java/test/test/runtime/api/interceptors/DefaultInterceptors.java", ", "README.md": "# com.aws.pdk.test -Data Types +composite models - API version: 1.0.0 No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) @@ -6460,11 +6496,11 @@ public class Example { DefaultApi apiInstance = new DefaultApi(defaultClient); try { - DataTypes200Response result = apiInstance.dataTypes() + Wrapper result = apiInstance.opGet() .execute(); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling DefaultApi#dataTypes"); + System.err.println("Exception when calling DefaultApi#opGet"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); @@ -6481,18 +6517,30 @@ All URIs are relative to *http://localhost* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*DefaultApi* | [**dataTypes**](docs/DefaultApi.md#dataTypes) | **GET** /types | +*DefaultApi* | [**opGet**](docs/DefaultApi.md#opGet) | **GET** /op | ## Documentation for Models - - [DataTypes200Response](docs/DataTypes200Response.md) - - [DataTypes200ResponseMyAllOf](docs/DataTypes200ResponseMyAllOf.md) - - [DataTypes200ResponseMyAllOfAllOf](docs/DataTypes200ResponseMyAllOfAllOf.md) - - [DataTypes200ResponseMyAllOfAllOf1](docs/DataTypes200ResponseMyAllOfAllOf1.md) - - [DataTypes200ResponseMyAnyOf](docs/DataTypes200ResponseMyAnyOf.md) - - [DataTypes200ResponseMyNotNot](docs/DataTypes200ResponseMyNotNot.md) - - [DataTypes200ResponseMyOneOf](docs/DataTypes200ResponseMyOneOf.md) + - [A](docs/A.md) + - [AllOfInlineAndRefs](docs/AllOfInlineAndRefs.md) + - [AllOfInlineAndRefsAllOf](docs/AllOfInlineAndRefsAllOf.md) + - [AllOfInlineAndRefsAllOf1](docs/AllOfInlineAndRefsAllOf1.md) + - [AllOfRefs](docs/AllOfRefs.md) + - [AnyOfInlineAndRefs](docs/AnyOfInlineAndRefs.md) + - [AnyOfPrimitives](docs/AnyOfPrimitives.md) + - [AnyOfPrimitivesAndRefs](docs/AnyOfPrimitivesAndRefs.md) + - [AnyOfRefs](docs/AnyOfRefs.md) + - [B](docs/B.md) + - [C](docs/C.md) + - [OneOfInlineAndRefs](docs/OneOfInlineAndRefs.md) + - [OneOfPrimitives](docs/OneOfPrimitives.md) + - [OneOfPrimitivesAndRefs](docs/OneOfPrimitivesAndRefs.md) + - [OneOfRefs](docs/OneOfRefs.md) + - [Wrapper](docs/Wrapper.md) + - [WrapperAllOf](docs/WrapperAllOf.md) + - [WrapperAnyOf](docs/WrapperAnyOf.md) + - [WrapperOneOf](docs/WrapperOneOf.md) ## Documentation for Authorization @@ -6511,235 +6559,247 @@ It's recommended to create an instance of \`ApiClient\` per thread in a multithr ", "api/openapi.yaml": "openapi: 3.0.3 info: - title: Data Types + title: composite models version: 1.0.0 servers: - url: / paths: - /types: + /op: get: - operationId: dataTypes responses: "200": content: application/json: schema: - $ref: '#/components/schemas/dataTypes_200_response' - description: Ok + $ref: '#/components/schemas/Wrapper' + description: Successful response x-accepts: application/json components: schemas: - dataTypes_200_response_myAllOf_allOf_1: + A: properties: - second: + a: type: string + required: + - a type: object - dataTypes_200_response_myOneOf: - oneOf: - - type: string - - type: number - dataTypes_200_response_myAllOf: - allOf: - - $ref: '#/components/schemas/dataTypes_200_response_myAllOf_allOf' - - $ref: '#/components/schemas/dataTypes_200_response_myAllOf_allOf_1' - dataTypes_200_response_myAllOf_allOf: + B: properties: - first: + b: type: string + required: + - b type: object - dataTypes_200_response: + C: properties: - myInt: - maximum: 7 - minimum: 3 - type: integer - myString: - type: string - myStringLength: - maxLength: 5 - minLength: 4 - type: string - myLongMinStringLength: - minLength: 1000 - type: string - myBool: - type: boolean - myNumber: - type: number - myDateArray: - items: - format: date - type: string - type: array - myEmail: - format: email - type: string - myUrl: - format: uri - type: string - myHostname: - format: hostname - type: string - myIpv4: - format: ipv4 - type: string - myIpv6: - format: ipv6 - type: string - myUuid: - format: uuid - type: string - myByte: - format: byte - type: string - myDateTime: - format: date-time - type: string - myRegexPattern: - pattern: "^\\\\d{4}-pattern-[a-z]+$" + c: type: string - myOneOf: - $ref: '#/components/schemas/dataTypes_200_response_myOneOf' - myAnyOf: - $ref: '#/components/schemas/dataTypes_200_response_myAnyOf' - myAllOf: - $ref: '#/components/schemas/dataTypes_200_response_myAllOf' - myNot: - not: - $ref: '#/components/schemas/dataTypes_200_response_myNot_not' - myNotString: - not: - type: string - myAdditionalProperties: - additionalProperties: - items: - maximum: 20 - minimum: 10 - type: integer - maxItems: 5 - minItems: 2 - type: array - type: object + required: + - c type: object - dataTypes_200_response_myAnyOf: + AllOfInlineAndRefs: + allOf: + - $ref: '#/components/schemas/AllOfInlineAndRefs_allOf' + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + - $ref: '#/components/schemas/AllOfInlineAndRefs_allOf_1' + AllOfRefs: + allOf: + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + AnyOfPrimitives: anyOf: - type: string - - type: number - dataTypes_200_response_myNot_not: + - type: integer + AnyOfPrimitivesAndRefs: + anyOf: + - type: string + - $ref: '#/components/schemas/A' + AnyOfRefs: + anyOf: + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + AnyOfInlineAndRefs: + anyOf: + - $ref: '#/components/schemas/AllOfInlineAndRefs_allOf' + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + - $ref: '#/components/schemas/AllOfInlineAndRefs_allOf_1' + OneOfPrimitives: + oneOf: + - type: string + - type: integer + OneOfPrimitivesAndRefs: + oneOf: + - type: string + - $ref: '#/components/schemas/A' + OneOfRefs: + oneOf: + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + OneOfInlineAndRefs: + oneOf: + - $ref: '#/components/schemas/AllOfInlineAndRefs_allOf' + - $ref: '#/components/schemas/A' + - $ref: '#/components/schemas/B' + - $ref: '#/components/schemas/C' + - $ref: '#/components/schemas/AllOfInlineAndRefs_allOf_1' + Wrapper: properties: - foo: + allOf: + $ref: '#/components/schemas/Wrapper_allOf' + anyOf: + $ref: '#/components/schemas/Wrapper_anyOf' + oneOf: + $ref: '#/components/schemas/Wrapper_oneOf' + type: object + AllOfInlineAndRefs_allOf: + properties: + d: + type: string + required: + - d + type: object + example: null + AllOfInlineAndRefs_allOf_1: + properties: + e: type: string type: object + example: null + Wrapper_allOf: + properties: + refs: + $ref: '#/components/schemas/AllOfRefs' + inlineAndRefs: + $ref: '#/components/schemas/AllOfInlineAndRefs' + type: object + Wrapper_anyOf: + properties: + refs: + $ref: '#/components/schemas/AnyOfRefs' + inlineAndRefs: + $ref: '#/components/schemas/AnyOfInlineAndRefs' + primitives: + $ref: '#/components/schemas/AnyOfPrimitives' + primitivesAndRefs: + $ref: '#/components/schemas/AnyOfPrimitivesAndRefs' + type: object + Wrapper_oneOf: + properties: + refs: + $ref: '#/components/schemas/OneOfRefs' + inlineAndRefs: + $ref: '#/components/schemas/OneOfInlineAndRefs' + primitives: + $ref: '#/components/schemas/OneOfPrimitives' + primitivesAndRefs: + $ref: '#/components/schemas/OneOfPrimitivesAndRefs' + type: object ", - "docs/DataTypes200Response.md": " + "docs/A.md": " -# DataTypes200Response +# A ## Properties | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -|**myInt** | **Integer** | | [optional] | -|**myString** | **String** | | [optional] | -|**myStringLength** | **String** | | [optional] | -|**myLongMinStringLength** | **String** | | [optional] | -|**myBool** | **Boolean** | | [optional] | -|**myNumber** | **BigDecimal** | | [optional] | -|**myDateArray** | **List<LocalDate>** | | [optional] | -|**myEmail** | **String** | | [optional] | -|**myUrl** | **URI** | | [optional] | -|**myHostname** | **String** | | [optional] | -|**myIpv4** | **String** | | [optional] | -|**myIpv6** | **String** | | [optional] | -|**myUuid** | **UUID** | | [optional] | -|**myByte** | **byte[]** | | [optional] | -|**myDateTime** | **OffsetDateTime** | | [optional] | -|**myRegexPattern** | **String** | | [optional] | -|**myOneOf** | [**DataTypes200ResponseMyOneOf**](DataTypes200ResponseMyOneOf.md) | | [optional] | -|**myAnyOf** | [**DataTypes200ResponseMyAnyOf**](DataTypes200ResponseMyAnyOf.md) | | [optional] | -|**myAllOf** | [**DataTypes200ResponseMyAllOf**](DataTypes200ResponseMyAllOf.md) | | [optional] | -|**myNot** | **Object** | | [optional] | -|**myNotString** | **Object** | | [optional] | -|**myAdditionalProperties** | **Map<String, List<Integer>>** | | [optional] | +|**a** | **String** | | | ", - "docs/DataTypes200ResponseMyAllOf.md": " + "docs/AllOfInlineAndRefs.md": " -# DataTypes200ResponseMyAllOf +# AllOfInlineAndRefs ## Properties | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -|**first** | **String** | | [optional] | -|**second** | **String** | | [optional] | +|**d** | **String** | | | +|**a** | **String** | | | +|**b** | **String** | | | +|**c** | **String** | | | +|**e** | **String** | | [optional] | ", - "docs/DataTypes200ResponseMyAllOfAllOf.md": " + "docs/AllOfInlineAndRefsAllOf.md": " -# DataTypes200ResponseMyAllOfAllOf +# AllOfInlineAndRefsAllOf ## Properties | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -|**first** | **String** | | [optional] | +|**d** | **String** | | | ", - "docs/DataTypes200ResponseMyAllOfAllOf1.md": " + "docs/AllOfInlineAndRefsAllOf1.md": " -# DataTypes200ResponseMyAllOfAllOf1 +# AllOfInlineAndRefsAllOf1 ## Properties | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -|**second** | **String** | | [optional] | +|**e** | **String** | | [optional] | ", - "docs/DataTypes200ResponseMyAnyOf.md": " + "docs/AllOfRefs.md": " -# DataTypes200ResponseMyAnyOf +# AllOfRefs ## Properties | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| +|**a** | **String** | | | +|**b** | **String** | | | +|**c** | **String** | | | ", - "docs/DataTypes200ResponseMyNotNot.md": " + "docs/AnyOfInlineAndRefs.md": " -# DataTypes200ResponseMyNotNot +# AnyOfInlineAndRefs ## Properties | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -|**foo** | **String** | | [optional] | +|**d** | **String** | | | +|**a** | **String** | | | +|**b** | **String** | | | +|**c** | **String** | | | +|**e** | **String** | | [optional] | ", - "docs/DataTypes200ResponseMyOneOf.md": " + "docs/AnyOfPrimitives.md": " -# DataTypes200ResponseMyOneOf +# AnyOfPrimitives ## Properties @@ -6750,57 +6810,115 @@ components: ", - "docs/DefaultApi.md": "# DefaultApi + "docs/AnyOfPrimitivesAndRefs.md": " -All URIs are relative to *http://localhost* +# AnyOfPrimitivesAndRefs -| Method | HTTP request | Description | -|------------- | ------------- | -------------| -| [**dataTypes**](DefaultApi.md#dataTypes) | **GET** /types | | +## Properties - -# **dataTypes** -> DataTypes200Response dataTypes().execute(); +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**a** | **String** | | | -### Example -\`\`\`java -// Import classes: -import test.test.runtime.ApiClient; -import test.test.runtime.ApiException; -import test.test.runtime.Configuration; -import test.test.runtime.models.*; -import test.test.runtime.api.DefaultApi; +", + "docs/AnyOfRefs.md": " -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://localhost"); +# AnyOfRefs - DefaultApi apiInstance = new DefaultApi(defaultClient); - try { - DataTypes200Response result = apiInstance.dataTypes() - .execute(); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling DefaultApi#dataTypes"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -\`\`\` -### Parameters -This endpoint does not need any parameter. +## Properties -### Return type +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**a** | **String** | | | +|**b** | **String** | | | +|**c** | **String** | | | -[**DataTypes200Response**](DataTypes200Response.md) + + +", + "docs/B.md": " + +# B + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**b** | **String** | | | + + + +", + "docs/C.md": " + +# C + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**c** | **String** | | | + + + +", + "docs/DefaultApi.md": "# DefaultApi + +All URIs are relative to *http://localhost* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**opGet**](DefaultApi.md#opGet) | **GET** /op | | + + + +# **opGet** +> Wrapper opGet().execute(); + + + +### Example +\`\`\`java +// Import classes: +import test.test.runtime.ApiClient; +import test.test.runtime.ApiException; +import test.test.runtime.Configuration; +import test.test.runtime.models.*; +import test.test.runtime.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + Wrapper result = apiInstance.opGet() + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#opGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +\`\`\` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Wrapper**](Wrapper.md) ### Authorization @@ -6814,7 +6932,133 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | Ok | - | +| **200** | Successful response | - | + +", + "docs/OneOfInlineAndRefs.md": " + +# OneOfInlineAndRefs + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**d** | **String** | | | +|**a** | **String** | | | +|**b** | **String** | | | +|**c** | **String** | | | +|**e** | **String** | | [optional] | + + + +", + "docs/OneOfPrimitives.md": " + +# OneOfPrimitives + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + +", + "docs/OneOfPrimitivesAndRefs.md": " + +# OneOfPrimitivesAndRefs + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**a** | **String** | | | + + + +", + "docs/OneOfRefs.md": " + +# OneOfRefs + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**a** | **String** | | | +|**b** | **String** | | | +|**c** | **String** | | | + + + +", + "docs/Wrapper.md": " + +# Wrapper + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**allOf** | [**WrapperAllOf**](WrapperAllOf.md) | | [optional] | +|**anyOf** | [**WrapperAnyOf**](WrapperAnyOf.md) | | [optional] | +|**oneOf** | [**WrapperOneOf**](WrapperOneOf.md) | | [optional] | + + + +", + "docs/WrapperAllOf.md": " + +# WrapperAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**refs** | [**AllOfRefs**](AllOfRefs.md) | | [optional] | +|**inlineAndRefs** | [**AllOfInlineAndRefs**](AllOfInlineAndRefs.md) | | [optional] | + + + +", + "docs/WrapperAnyOf.md": " + +# WrapperAnyOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**refs** | [**AnyOfRefs**](AnyOfRefs.md) | | [optional] | +|**inlineAndRefs** | [**AnyOfInlineAndRefs**](AnyOfInlineAndRefs.md) | | [optional] | +|**primitives** | [**AnyOfPrimitives**](AnyOfPrimitives.md) | | [optional] | +|**primitivesAndRefs** | [**AnyOfPrimitivesAndRefs**](AnyOfPrimitivesAndRefs.md) | | [optional] | + + + +", + "docs/WrapperOneOf.md": " + +# WrapperOneOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**refs** | [**OneOfRefs**](OneOfRefs.md) | | [optional] | +|**inlineAndRefs** | [**OneOfInlineAndRefs**](OneOfInlineAndRefs.md) | | [optional] | +|**primitives** | [**OneOfPrimitives**](OneOfPrimitives.md) | | [optional] | +|**primitivesAndRefs** | [**OneOfPrimitivesAndRefs**](OneOfPrimitivesAndRefs.md) | | [optional] | + + ", "openapitools.json": "{ @@ -6828,7 +7072,7 @@ No authorization required } ", "src/main/java/test/test/runtime/ApiCallback.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -6891,7 +7135,7 @@ public interface ApiCallback { } ", "src/main/java/test/test/runtime/ApiClient.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -8438,7 +8682,7 @@ public class ApiClient { } ", "src/main/java/test/test/runtime/ApiException.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -8605,7 +8849,7 @@ public class ApiException extends Exception { } ", "src/main/java/test/test/runtime/ApiResponse.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -8682,7 +8926,7 @@ public class ApiResponse { } ", "src/main/java/test/test/runtime/Configuration.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -8722,7 +8966,7 @@ public class Configuration { } ", "src/main/java/test/test/runtime/GzipRequestInterceptor.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -8808,7 +9052,7 @@ class GzipRequestInterceptor implements Interceptor { } ", "src/main/java/test/test/runtime/JSON.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -8902,13 +9146,25 @@ 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.DataTypes200Response.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAllOf.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAllOfAllOf.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAllOfAllOf1.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAnyOf.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyNotNot.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyOneOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.A.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AllOfInlineAndRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AllOfInlineAndRefsAllOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AllOfInlineAndRefsAllOf1.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AllOfRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AnyOfInlineAndRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AnyOfPrimitives.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AnyOfPrimitivesAndRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AnyOfRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.B.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.C.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.OneOfInlineAndRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.OneOfPrimitives.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.OneOfPrimitivesAndRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.OneOfRefs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.Wrapper.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.WrapperAllOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.WrapperAnyOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.WrapperOneOf.CustomTypeAdapterFactory()); gson = gsonBuilder.create(); } @@ -9216,7 +9472,7 @@ public class JSON { } ", "src/main/java/test/test/runtime/Pair.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -9274,7 +9530,7 @@ public class Pair { } ", "src/main/java/test/test/runtime/ProgressRequestBody.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -9348,7 +9604,7 @@ public class ProgressRequestBody extends RequestBody { } ", "src/main/java/test/test/runtime/ProgressResponseBody.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -9502,7 +9758,7 @@ public class ServerVariable { } ", "src/main/java/test/test/runtime/StringUtil.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -9586,7 +9842,7 @@ public class StringUtil { } ", "src/main/java/test/test/runtime/api/DefaultApi.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -9614,7 +9870,7 @@ import com.google.gson.reflect.TypeToken; import java.io.IOException; -import test.test.runtime.model.DataTypes200Response; +import test.test.runtime.model.Wrapper; import java.lang.reflect.Type; import java.util.ArrayList; @@ -9660,7 +9916,7 @@ public class DefaultApi { this.localCustomBaseUrl = customBaseUrl; } - private okhttp3.Call dataTypesCall(final ApiCallback _callback) throws ApiException { + private okhttp3.Call opGetCall(final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -9677,7 +9933,7 @@ public class DefaultApi { Object localVarPostBody = null; // create path and map variables - String localVarPath = "/types"; + String localVarPath = "/op"; List localVarQueryParams = new ArrayList(); List localVarCollectionQueryParams = new ArrayList(); @@ -9705,103 +9961,103 @@ public class DefaultApi { } @SuppressWarnings("rawtypes") - private okhttp3.Call dataTypesValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return dataTypesCall(_callback); + private okhttp3.Call opGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return opGetCall(_callback); } - private ApiResponse dataTypesWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = dataTypesValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); + private ApiResponse opGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = opGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } - private okhttp3.Call dataTypesAsync(final ApiCallback _callback) throws ApiException { + private okhttp3.Call opGetAsync(final ApiCallback _callback) throws ApiException { - okhttp3.Call localVarCall = dataTypesValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); + okhttp3.Call localVarCall = opGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } - public class APIdataTypesRequest { + public class APIopGetRequest { - private APIdataTypesRequest() { + private APIopGetRequest() { } /** - * Build call for dataTypes + * Build call for opGet * @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 -
200 Successful response -
*/ public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { - return dataTypesCall(_callback); + return opGetCall(_callback); } /** - * Execute dataTypes request - * @return DataTypes200Response + * Execute opGet request + * @return Wrapper * @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 -
200 Successful response -
*/ - public DataTypes200Response execute() throws ApiException { - ApiResponse localVarResp = dataTypesWithHttpInfo(); + public Wrapper execute() throws ApiException { + ApiResponse localVarResp = opGetWithHttpInfo(); return localVarResp.getData(); } /** - * Execute dataTypes request with HTTP info returned - * @return ApiResponse<DataTypes200Response> + * Execute opGet request with HTTP info returned + * @return ApiResponse<Wrapper> * @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 -
200 Successful response -
*/ - public ApiResponse executeWithHttpInfo() throws ApiException { - return dataTypesWithHttpInfo(); + public ApiResponse executeWithHttpInfo() throws ApiException { + return opGetWithHttpInfo(); } /** - * Execute dataTypes request (asynchronously) + * Execute opGet 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 -
200 Successful response -
*/ - public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { - return dataTypesAsync(_callback); + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return opGetAsync(_callback); } } /** * * - * @return APIdataTypesRequest + * @return APIopGetRequest * @http.response.details - +
Status Code Description Response Headers
200 Ok -
200 Successful response -
*/ - public APIdataTypesRequest dataTypes() { - return new APIdataTypesRequest(); + public APIopGetRequest opGet() { + return new APIopGetRequest(); } } ", @@ -9850,7 +10106,7 @@ 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.data_types.*; +import test.test.runtime.api.handlers.op_get.*; import test.test.runtime.api.handlers.Handlers; import test.test.runtime.api.handlers.*; @@ -9868,17 +10124,17 @@ import java.util.Collections; public abstract class HandlerRouter implements RequestHandler { - private static final String dataTypesMethodAndPath = Handlers.concatMethodAndPath("GET", "/types"); + private static final String opGetMethodAndPath = Handlers.concatMethodAndPath("GET", "/op"); - private final DataTypes constructedDataTypes; + private final OpGet constructedOpGet; /** - * This method must return your implementation of the DataTypes operation + * This method must return your implementation of the OpGet operation */ - public abstract DataTypes dataTypes(); + public abstract OpGet opGet(); private static enum Route { - dataTypesRoute, + opGetRoute, } /** @@ -9887,11 +10143,11 @@ public abstract class HandlerRouter implements RequestHandler routes = new HashMap<>(); public HandlerRouter() { - this.routes.put(dataTypesMethodAndPath, Route.dataTypesRoute); + this.routes.put(opGetMethodAndPath, Route.opGetRoute); // 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.constructedDataTypes = this.dataTypes(); + this.constructedOpGet = this.opGet(); } /** @@ -9911,10 +10167,10 @@ public abstract class HandlerRouter implements RequestHandler> dataTypesInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); - dataTypesInterceptors.addAll(this.getInterceptors()); - return this.constructedDataTypes.handleRequestWithAdditionalInterceptors(event, context, dataTypesInterceptors); + case opGetRoute: + List> opGetInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + opGetInterceptors.addAll(this.getInterceptors()); + return this.constructedOpGet.handleRequestWithAdditionalInterceptors(event, context, opGetInterceptors); default: throw new RuntimeException(String.format("No registered handler for method {} and path {}", method, path)); } @@ -9953,7 +10209,7 @@ import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import test.test.runtime.model.DataTypes200Response; +import test.test.runtime.model.Wrapper; import test.test.runtime.JSON; @@ -10580,8 +10836,8 @@ public interface Response { Map> getMultiValueHeaders(); } ", - "src/main/java/test/test/runtime/api/handlers/data_types/DataTypes.java": " -package test.test.runtime.api.handlers.data_types; + "src/main/java/test/test/runtime/api/handlers/op_get/OpGet.java": " +package test.test.runtime.api.handlers.op_get; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -10605,50 +10861,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the dataTypes operation + * Lambda handler wrapper for the opGet operation */ -public abstract class DataTypes implements RequestHandler, Resource { +public abstract class OpGet implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the dataTypes operation + * Handle the request for the opGet operation */ - public abstract DataTypesResponse handle(final DataTypesRequestInput request); + public abstract OpGetResponse handle(final OpGetRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(DataTypes.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(OpGet.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 DataTypesRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new OpGetRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final DataTypesInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final OpGetInput 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 @@ -10667,7 +10923,7 @@ public abstract class DataTypes implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -10728,20 +10984,20 @@ public abstract class DataTypes implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "dataTypes"); + interceptorContext.put("operationId", "opGet"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - DataTypesInput input; + OpGetInput input; try { - input = new DataTypesInput(event); + input = new OpGetInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -10766,8 +11022,8 @@ public abstract class DataTypes implements RequestHandler headers; private final Map> multiValueHeaders; - private DataTypes200Response(final DataTypes200Response body, final Map headers, final Map> multiValueHeaders) { + private OpGet200Response(final Wrapper body, final Map headers, final Map> multiValueHeaders) { this.typedBody = body; this.body = body.toJson(); this.headers = headers; @@ -10809,7 +11065,7 @@ public class DataTypes200Response extends RuntimeException implements DataTypesR return this.body; } - public DataTypes200Response getTypedBody() { + public Wrapper getTypedBody() { return this.typedBody; } @@ -10824,29 +11080,29 @@ public class DataTypes200Response extends RuntimeException implements DataTypesR } /** - * Create a DataTypes200Response with a body + * Create a OpGet200Response with a body */ - public static DataTypes200Response of(final DataTypes200Response body) { - return new DataTypes200Response(body, new HashMap<>(), new HashMap<>()); + public static OpGet200Response of(final Wrapper body) { + return new OpGet200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a DataTypes200Response with a body and headers + * Create a OpGet200Response with a body and headers */ - public static DataTypes200Response of(final DataTypes200Response body, final Map headers) { - return new DataTypes200Response(body, headers, new HashMap<>()); + public static OpGet200Response of(final Wrapper body, final Map headers) { + return new OpGet200Response(body, headers, new HashMap<>()); } /** - * Create a DataTypes200Response with a body, headers and multi-value headers + * Create a OpGet200Response with a body, headers and multi-value headers */ - public static DataTypes200Response of(final DataTypes200Response body, final Map headers, final Map> multiValueHeaders) { - return new DataTypes200Response(body, headers, multiValueHeaders); + public static OpGet200Response of(final Wrapper body, final Map headers, final Map> multiValueHeaders) { + return new OpGet200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/data_types/DataTypesInput.java": " -package test.test.runtime.api.handlers.data_types; + "src/main/java/test/test/runtime/api/handlers/op_get/OpGetInput.java": " +package test.test.runtime.api.handlers.op_get; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -10859,11 +11115,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the dataTypes operation + * Input for the opGet operation */ @lombok.Builder @lombok.AllArgsConstructor -public class DataTypesInput { +public class OpGetInput { 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. @@ -10872,20 +11128,20 @@ public class DataTypesInput { } } - private final DataTypesRequestParameters requestParameters; + private final OpGetRequestParameters requestParameters; - public DataTypesInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new DataTypesRequestParameters(event); + public OpGetInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new OpGetRequestParameters(event); } - public DataTypesRequestParameters getRequestParameters() { + public OpGetRequestParameters getRequestParameters() { return this.requestParameters; } } ", - "src/main/java/test/test/runtime/api/handlers/data_types/DataTypesRequestInput.java": " -package test.test.runtime.api.handlers.data_types; + "src/main/java/test/test/runtime/api/handlers/op_get/OpGetRequestInput.java": " +package test.test.runtime.api.handlers.op_get; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -10898,20 +11154,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the dataTypes operation, including the raw API Gateway event + * Full request input for the opGet operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class DataTypesRequestInput implements RequestInput { +public class OpGetRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final DataTypesInput input; + private final OpGetInput input; /** * Returns the typed request input, with path, query and body parameters */ - public DataTypesInput getInput() { + public OpGetInput getInput() { return this.input; } @@ -10937,8 +11193,8 @@ public class DataTypesRequestInput implements RequestInput { } } ", - "src/main/java/test/test/runtime/api/handlers/data_types/DataTypesRequestParameters.java": " -package test.test.runtime.api.handlers.data_types; + "src/main/java/test/test/runtime/api/handlers/op_get/OpGetRequestParameters.java": " +package test.test.runtime.api.handlers.op_get; import test.test.runtime.api.handlers.Handlers; import java.util.Optional; @@ -10952,13 +11208,13 @@ import java.math.BigInteger; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; /** - * Query, path and header parameters for the DataTypes operation + * Query, path and header parameters for the OpGet operation */ @lombok.Builder @lombok.AllArgsConstructor -public class DataTypesRequestParameters { +public class OpGetRequestParameters { - public DataTypesRequestParameters(final APIGatewayProxyRequestEvent event) { + public OpGetRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -10974,15 +11230,15 @@ public class DataTypesRequestParameters { } ", - "src/main/java/test/test/runtime/api/handlers/data_types/DataTypesResponse.java": " -package test.test.runtime.api.handlers.data_types; + "src/main/java/test/test/runtime/api/handlers/op_get/OpGetResponse.java": " +package test.test.runtime.api.handlers.op_get; import test.test.runtime.api.handlers.Response; /** - * Response for the dataTypes operation + * Response for the opGet operation */ -public interface DataTypesResponse extends Response {} +public interface OpGetResponse extends Response {} ", "src/main/java/test/test/runtime/api/interceptors/DefaultInterceptors.java": "package test.test.runtime.api.interceptors; @@ -11329,7 +11585,7 @@ public class TracingInterceptor extends InterceptorWithWarmup { import test.test.runtime.model.*; -import test.test.runtime.model.DataTypes200Response; +import test.test.runtime.model.Wrapper; import java.util.HashMap; import java.util.Map; @@ -11338,11 +11594,11 @@ import java.util.Map; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") @lombok.Builder @lombok.Getter public class OperationConfig { - private T dataTypes; + private T opGet; public Map asMap() { Map map = new HashMap<>(); - map.put("dataTypes", this.dataTypes); + map.put("opGet", this.opGet); return map; } } @@ -11351,7 +11607,7 @@ public class OperationConfig { import test.test.runtime.model.*; -import test.test.runtime.model.DataTypes200Response; +import test.test.runtime.model.Wrapper; import java.util.HashMap; import java.util.Map; @@ -11375,8 +11631,8 @@ public class OperationLookup { public static Map getOperationLookup() { final Map config = new HashMap<>(); - config.put("dataTypes", OperationLookupEntry.builder() - .path("/types") + config.put("opGet", OperationLookupEntry.builder() + .path("/op") .method("GET") .contentTypes(Arrays.asList("application/json")) .build()); @@ -11396,13 +11652,13 @@ public class Operations { */ public static OperationConfig.OperationConfigBuilder all(final T value) { return OperationConfig.builder() - .dataTypes(value) + .opGet(value) ; } } ", "src/main/java/test/test/runtime/auth/ApiKeyAuth.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -11483,7 +11739,7 @@ public class ApiKeyAuth implements Authentication { } ", "src/main/java/test/test/runtime/auth/Authentication.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -11520,7 +11776,7 @@ public interface Authentication { } ", "src/main/java/test/test/runtime/auth/HttpBasicAuth.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -11578,7 +11834,7 @@ public class HttpBasicAuth implements Authentication { } ", "src/main/java/test/test/runtime/auth/HttpBearerAuth.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -11640,9 +11896,224 @@ public class HttpBearerAuth implements Authentication { return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; } } +", + "src/main/java/test/test/runtime/model/A.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * A + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class A { + public static final String SERIALIZED_NAME_A = "a"; + @SerializedName(SERIALIZED_NAME_A) + private String a; + + public A() { + } + + public A a(String a) { + + this.a = a; + return this; + } + + /** + * Get a + * @return a + **/ + @javax.annotation.Nonnull + + public String getA() { + return a; + } + + + public void setA(String a) { + this.a = a; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + A A = (A) o; + return Objects.equals(this.a, A.a); + } + + @Override + public int hashCode() { + return Objects.hash(a); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class A {\\n"); + sb.append(" a: ").append(toIndentedString(a)).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("a"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("a"); + } + + /** + * 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 A + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!A.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in A is not found in the empty JSON string", A.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!A.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`A\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : A.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("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())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!A.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'A' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(A.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, A value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public A read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of A given an JSON string + * + * @param jsonString JSON string + * @return An instance of A + * @throws IOException if the JSON string is invalid with respect to A + */ + public static A fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, A.class); + } + + /** + * Convert an instance of A to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + ", "src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java": "/* - * Data Types + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -11792,8 +12263,8 @@ public abstract class AbstractOpenApiSchema { } ", - "src/main/java/test/test/runtime/model/DataTypes200Response.java": "/* - * Data Types + "src/main/java/test/test/runtime/model/AllOfInlineAndRefs.java": "/* + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -11815,19 +12286,6 @@ import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.math.BigDecimal; -import java.net.URI; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import org.openapitools.jackson.nullable.JsonNullable; -import test.test.runtime.model.DataTypes200ResponseMyAllOf; -import test.test.runtime.model.DataTypes200ResponseMyAnyOf; -import test.test.runtime.model.DataTypes200ResponseMyOneOf; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -11851,601 +12309,598 @@ import java.util.Set; import test.test.runtime.JSON; /** - * DataTypes200Response + * AllOfInlineAndRefs */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DataTypes200Response { - public static final String SERIALIZED_NAME_MY_INT = "myInt"; - @SerializedName(SERIALIZED_NAME_MY_INT) - private Integer myInt; - - public static final String SERIALIZED_NAME_MY_STRING = "myString"; - @SerializedName(SERIALIZED_NAME_MY_STRING) - private String myString; - - public static final String SERIALIZED_NAME_MY_STRING_LENGTH = "myStringLength"; - @SerializedName(SERIALIZED_NAME_MY_STRING_LENGTH) - private String myStringLength; - - public static final String SERIALIZED_NAME_MY_LONG_MIN_STRING_LENGTH = "myLongMinStringLength"; - @SerializedName(SERIALIZED_NAME_MY_LONG_MIN_STRING_LENGTH) - private String myLongMinStringLength; - - public static final String SERIALIZED_NAME_MY_BOOL = "myBool"; - @SerializedName(SERIALIZED_NAME_MY_BOOL) - private Boolean myBool; - - public static final String SERIALIZED_NAME_MY_NUMBER = "myNumber"; - @SerializedName(SERIALIZED_NAME_MY_NUMBER) - private BigDecimal myNumber; - - public static final String SERIALIZED_NAME_MY_DATE_ARRAY = "myDateArray"; - @SerializedName(SERIALIZED_NAME_MY_DATE_ARRAY) - private List myDateArray = null; - - public static final String SERIALIZED_NAME_MY_EMAIL = "myEmail"; - @SerializedName(SERIALIZED_NAME_MY_EMAIL) - private String myEmail; - - public static final String SERIALIZED_NAME_MY_URL = "myUrl"; - @SerializedName(SERIALIZED_NAME_MY_URL) - private URI myUrl; - - public static final String SERIALIZED_NAME_MY_HOSTNAME = "myHostname"; - @SerializedName(SERIALIZED_NAME_MY_HOSTNAME) - private String myHostname; - - public static final String SERIALIZED_NAME_MY_IPV4 = "myIpv4"; - @SerializedName(SERIALIZED_NAME_MY_IPV4) - private String myIpv4; - - public static final String SERIALIZED_NAME_MY_IPV6 = "myIpv6"; - @SerializedName(SERIALIZED_NAME_MY_IPV6) - private String myIpv6; - - public static final String SERIALIZED_NAME_MY_UUID = "myUuid"; - @SerializedName(SERIALIZED_NAME_MY_UUID) - private UUID myUuid; - - public static final String SERIALIZED_NAME_MY_BYTE = "myByte"; - @SerializedName(SERIALIZED_NAME_MY_BYTE) - private byte[] myByte; - - public static final String SERIALIZED_NAME_MY_DATE_TIME = "myDateTime"; - @SerializedName(SERIALIZED_NAME_MY_DATE_TIME) - private OffsetDateTime myDateTime; - - public static final String SERIALIZED_NAME_MY_REGEX_PATTERN = "myRegexPattern"; - @SerializedName(SERIALIZED_NAME_MY_REGEX_PATTERN) - private String myRegexPattern; - - public static final String SERIALIZED_NAME_MY_ONE_OF = "myOneOf"; - @SerializedName(SERIALIZED_NAME_MY_ONE_OF) - private DataTypes200ResponseMyOneOf myOneOf; - - public static final String SERIALIZED_NAME_MY_ANY_OF = "myAnyOf"; - @SerializedName(SERIALIZED_NAME_MY_ANY_OF) - private DataTypes200ResponseMyAnyOf myAnyOf; +public class AllOfInlineAndRefs { + public static final String SERIALIZED_NAME_D = "d"; + @SerializedName(SERIALIZED_NAME_D) + private String d; - public static final String SERIALIZED_NAME_MY_ALL_OF = "myAllOf"; - @SerializedName(SERIALIZED_NAME_MY_ALL_OF) - private DataTypes200ResponseMyAllOf myAllOf; + public static final String SERIALIZED_NAME_A = "a"; + @SerializedName(SERIALIZED_NAME_A) + private String a; - public static final String SERIALIZED_NAME_MY_NOT = "myNot"; - @SerializedName(SERIALIZED_NAME_MY_NOT) - private Object myNot = null; + public static final String SERIALIZED_NAME_B = "b"; + @SerializedName(SERIALIZED_NAME_B) + private String b; - public static final String SERIALIZED_NAME_MY_NOT_STRING = "myNotString"; - @SerializedName(SERIALIZED_NAME_MY_NOT_STRING) - private Object myNotString = null; + public static final String SERIALIZED_NAME_C = "c"; + @SerializedName(SERIALIZED_NAME_C) + private String c; - public static final String SERIALIZED_NAME_MY_ADDITIONAL_PROPERTIES = "myAdditionalProperties"; - @SerializedName(SERIALIZED_NAME_MY_ADDITIONAL_PROPERTIES) - private Map> myAdditionalProperties = null; + public static final String SERIALIZED_NAME_E = "e"; + @SerializedName(SERIALIZED_NAME_E) + private String e; - public DataTypes200Response() { + public AllOfInlineAndRefs() { } - public DataTypes200Response myInt(Integer myInt) { + public AllOfInlineAndRefs d(String d) { - this.myInt = myInt; + this.d = d; return this; } /** - * Get myInt - * minimum: 3 - * maximum: 7 - * @return myInt + * Get d + * @return d **/ - @javax.annotation.Nullable + @javax.annotation.Nonnull - public Integer getMyInt() { - return myInt; + public String getD() { + return d; } - public void setMyInt(Integer myInt) { - this.myInt = myInt; + public void setD(String d) { + this.d = d; } - public DataTypes200Response myString(String myString) { + public AllOfInlineAndRefs a(String a) { - this.myString = myString; + this.a = a; return this; } /** - * Get myString - * @return myString + * Get a + * @return a **/ - @javax.annotation.Nullable + @javax.annotation.Nonnull - public String getMyString() { - return myString; + public String getA() { + return a; } - public void setMyString(String myString) { - this.myString = myString; + public void setA(String a) { + this.a = a; } - public DataTypes200Response myStringLength(String myStringLength) { + public AllOfInlineAndRefs b(String b) { - this.myStringLength = myStringLength; + this.b = b; return this; } /** - * Get myStringLength - * @return myStringLength + * Get b + * @return b **/ - @javax.annotation.Nullable + @javax.annotation.Nonnull - public String getMyStringLength() { - return myStringLength; + public String getB() { + return b; } - public void setMyStringLength(String myStringLength) { - this.myStringLength = myStringLength; + public void setB(String b) { + this.b = b; } - public DataTypes200Response myLongMinStringLength(String myLongMinStringLength) { + public AllOfInlineAndRefs c(String c) { - this.myLongMinStringLength = myLongMinStringLength; + this.c = c; return this; } /** - * Get myLongMinStringLength - * @return myLongMinStringLength + * Get c + * @return c **/ - @javax.annotation.Nullable + @javax.annotation.Nonnull - public String getMyLongMinStringLength() { - return myLongMinStringLength; + public String getC() { + return c; } - public void setMyLongMinStringLength(String myLongMinStringLength) { - this.myLongMinStringLength = myLongMinStringLength; + public void setC(String c) { + this.c = c; } - public DataTypes200Response myBool(Boolean myBool) { + public AllOfInlineAndRefs e(String e) { - this.myBool = myBool; + this.e = e; return this; } /** - * Get myBool - * @return myBool + * Get e + * @return e **/ @javax.annotation.Nullable - public Boolean getMyBool() { - return myBool; + public String getE() { + return e; } - public void setMyBool(Boolean myBool) { - this.myBool = myBool; + public void setE(String e) { + this.e = e; } - public DataTypes200Response myNumber(BigDecimal myNumber) { - - this.myNumber = myNumber; - return this; - } - - /** - * Get myNumber - * @return myNumber - **/ - @javax.annotation.Nullable - public BigDecimal getMyNumber() { - return myNumber; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfInlineAndRefs allOfInlineAndRefs = (AllOfInlineAndRefs) o; + return Objects.equals(this.d, allOfInlineAndRefs.d) && + Objects.equals(this.a, allOfInlineAndRefs.a) && + Objects.equals(this.b, allOfInlineAndRefs.b) && + Objects.equals(this.c, allOfInlineAndRefs.c) && + Objects.equals(this.e, allOfInlineAndRefs.e); } - - public void setMyNumber(BigDecimal myNumber) { - this.myNumber = myNumber; + @Override + public int hashCode() { + return Objects.hash(d, a, b, c, e); } - - public DataTypes200Response myDateArray(List myDateArray) { - - this.myDateArray = myDateArray; - return this; + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfInlineAndRefs {\\n"); + sb.append(" d: ").append(toIndentedString(d)).append("\\n"); + sb.append(" a: ").append(toIndentedString(a)).append("\\n"); + sb.append(" b: ").append(toIndentedString(b)).append("\\n"); + sb.append(" c: ").append(toIndentedString(c)).append("\\n"); + sb.append(" e: ").append(toIndentedString(e)).append("\\n"); + sb.append("}"); + return sb.toString(); } - public DataTypes200Response addMyDateArrayItem(LocalDate myDateArrayItem) { - if (this.myDateArray == null) { - this.myDateArray = new ArrayList<>(); + /** + * 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"; } - this.myDateArray.add(myDateArrayItem); - return this; + return o.toString().replace("\\n", "\\n "); } - /** - * Get myDateArray - * @return myDateArray - **/ - @javax.annotation.Nullable - public List getMyDateArray() { - return myDateArray; - } + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("d"); + openapiFields.add("a"); + openapiFields.add("b"); + openapiFields.add("c"); + openapiFields.add("e"); - public void setMyDateArray(List myDateArray) { - this.myDateArray = myDateArray; + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("d"); + openapiRequiredFields.add("a"); + openapiRequiredFields.add("b"); + openapiRequiredFields.add("c"); } + /** + * 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 AllOfInlineAndRefs + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!AllOfInlineAndRefs.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AllOfInlineAndRefs is not found in the empty JSON string", AllOfInlineAndRefs.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!AllOfInlineAndRefs.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AllOfInlineAndRefs\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } - public DataTypes200Response myEmail(String myEmail) { - - this.myEmail = myEmail; - return this; + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AllOfInlineAndRefs.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("d").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`d\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("d").toString())); + } + if (!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())); + } + if (!jsonObj.get("b").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`b\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("b").toString())); + } + if (!jsonObj.get("c").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`c\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("c").toString())); + } + if ((jsonObj.get("e") != null && !jsonObj.get("e").isJsonNull()) && !jsonObj.get("e").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`e\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("e").toString())); + } } - /** - * Get myEmail - * @return myEmail - **/ - @javax.annotation.Nullable + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfInlineAndRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfInlineAndRefs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfInlineAndRefs.class)); - public String getMyEmail() { - return myEmail; - } + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfInlineAndRefs value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + @Override + public AllOfInlineAndRefs read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } - public void setMyEmail(String myEmail) { - this.myEmail = myEmail; + }.nullSafe(); + } } - - public DataTypes200Response myUrl(URI myUrl) { - - this.myUrl = myUrl; - return this; + /** + * Create an instance of AllOfInlineAndRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfInlineAndRefs + * @throws IOException if the JSON string is invalid with respect to AllOfInlineAndRefs + */ + public static AllOfInlineAndRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfInlineAndRefs.class); } - /** - * Get myUrl - * @return myUrl - **/ - @javax.annotation.Nullable - - public URI getMyUrl() { - return myUrl; + /** + * Convert an instance of AllOfInlineAndRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); } +} + +", + "src/main/java/test/test/runtime/model/AllOfInlineAndRefsAllOf.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ - public void setMyUrl(URI myUrl) { - this.myUrl = myUrl; - } +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; - public DataTypes200Response myHostname(String myHostname) { - - this.myHostname = myHostname; - return this; - } +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; - /** - * Get myHostname - * @return myHostname - **/ - @javax.annotation.Nullable +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; - public String getMyHostname() { - return myHostname; - } +import test.test.runtime.JSON; +/** + * AllOfInlineAndRefsAllOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AllOfInlineAndRefsAllOf { + public static final String SERIALIZED_NAME_D = "d"; + @SerializedName(SERIALIZED_NAME_D) + private String d; - public void setMyHostname(String myHostname) { - this.myHostname = myHostname; + public AllOfInlineAndRefsAllOf() { } - - public DataTypes200Response myIpv4(String myIpv4) { + public AllOfInlineAndRefsAllOf d(String d) { - this.myIpv4 = myIpv4; + this.d = d; return this; } /** - * Get myIpv4 - * @return myIpv4 + * Get d + * @return d **/ - @javax.annotation.Nullable + @javax.annotation.Nonnull - public String getMyIpv4() { - return myIpv4; + public String getD() { + return d; } - public void setMyIpv4(String myIpv4) { - this.myIpv4 = myIpv4; + public void setD(String d) { + this.d = d; } - public DataTypes200Response myIpv6(String myIpv6) { - - this.myIpv6 = myIpv6; - return this; - } - - /** - * Get myIpv6 - * @return myIpv6 - **/ - @javax.annotation.Nullable - public String getMyIpv6() { - return myIpv6; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfInlineAndRefsAllOf allOfInlineAndRefsAllOf = (AllOfInlineAndRefsAllOf) o; + return Objects.equals(this.d, allOfInlineAndRefsAllOf.d); } - - public void setMyIpv6(String myIpv6) { - this.myIpv6 = myIpv6; + @Override + public int hashCode() { + return Objects.hash(d); } - - public DataTypes200Response myUuid(UUID myUuid) { - - this.myUuid = myUuid; - return this; + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfInlineAndRefsAllOf {\\n"); + sb.append(" d: ").append(toIndentedString(d)).append("\\n"); + sb.append("}"); + return sb.toString(); } - /** - * Get myUuid - * @return myUuid - **/ - @javax.annotation.Nullable - - public UUID getMyUuid() { - return myUuid; + /** + * 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 void setMyUuid(UUID myUuid) { - this.myUuid = myUuid; - } + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("d"); - public DataTypes200Response myByte(byte[] myByte) { - - this.myByte = myByte; - return this; + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("d"); } - /** - * Get myByte - * @return myByte - **/ - @javax.annotation.Nullable - - public byte[] getMyByte() { - return myByte; - } + /** + * 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 AllOfInlineAndRefsAllOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!AllOfInlineAndRefsAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AllOfInlineAndRefsAllOf is not found in the empty JSON string", AllOfInlineAndRefsAllOf.openapiRequiredFields.toString())); + } + } + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!AllOfInlineAndRefsAllOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AllOfInlineAndRefsAllOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } - public void setMyByte(byte[] myByte) { - this.myByte = myByte; + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AllOfInlineAndRefsAllOf.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("d").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`d\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("d").toString())); + } } + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfInlineAndRefsAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfInlineAndRefsAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfInlineAndRefsAllOf.class)); - public DataTypes200Response myDateTime(OffsetDateTime myDateTime) { - - this.myDateTime = myDateTime; - return this; - } + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfInlineAndRefsAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } - /** - * Get myDateTime - * @return myDateTime - **/ - @javax.annotation.Nullable + @Override + public AllOfInlineAndRefsAllOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } - public OffsetDateTime getMyDateTime() { - return myDateTime; + }.nullSafe(); + } } - - public void setMyDateTime(OffsetDateTime myDateTime) { - this.myDateTime = myDateTime; + /** + * Create an instance of AllOfInlineAndRefsAllOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfInlineAndRefsAllOf + * @throws IOException if the JSON string is invalid with respect to AllOfInlineAndRefsAllOf + */ + public static AllOfInlineAndRefsAllOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfInlineAndRefsAllOf.class); } - - public DataTypes200Response myRegexPattern(String myRegexPattern) { - - this.myRegexPattern = myRegexPattern; - return this; - } - - /** - * Get myRegexPattern - * @return myRegexPattern - **/ - @javax.annotation.Nullable - - public String getMyRegexPattern() { - return myRegexPattern; - } - - - public void setMyRegexPattern(String myRegexPattern) { - this.myRegexPattern = myRegexPattern; - } - - - public DataTypes200Response myOneOf(DataTypes200ResponseMyOneOf myOneOf) { - - this.myOneOf = myOneOf; - return this; - } - - /** - * Get myOneOf - * @return myOneOf - **/ - @javax.annotation.Nullable - - public DataTypes200ResponseMyOneOf getMyOneOf() { - return myOneOf; - } - - - public void setMyOneOf(DataTypes200ResponseMyOneOf myOneOf) { - this.myOneOf = myOneOf; - } - - - public DataTypes200Response myAnyOf(DataTypes200ResponseMyAnyOf myAnyOf) { - - this.myAnyOf = myAnyOf; - return this; - } - - /** - * Get myAnyOf - * @return myAnyOf - **/ - @javax.annotation.Nullable - - public DataTypes200ResponseMyAnyOf getMyAnyOf() { - return myAnyOf; - } - - - public void setMyAnyOf(DataTypes200ResponseMyAnyOf myAnyOf) { - this.myAnyOf = myAnyOf; - } - - - public DataTypes200Response myAllOf(DataTypes200ResponseMyAllOf myAllOf) { - - this.myAllOf = myAllOf; - return this; - } - - /** - * Get myAllOf - * @return myAllOf - **/ - @javax.annotation.Nullable - - public DataTypes200ResponseMyAllOf getMyAllOf() { - return myAllOf; - } - - - public void setMyAllOf(DataTypes200ResponseMyAllOf myAllOf) { - this.myAllOf = myAllOf; - } - - - public DataTypes200Response myNot(Object myNot) { - - this.myNot = myNot; - return this; + /** + * Convert an instance of AllOfInlineAndRefsAllOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); } +} - /** - * Get myNot - * @return myNot - **/ - @javax.annotation.Nullable - - public Object getMyNot() { - return myNot; - } +", + "src/main/java/test/test/runtime/model/AllOfInlineAndRefsAllOf1.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ - public void setMyNot(Object myNot) { - this.myNot = myNot; - } +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; - public DataTypes200Response myNotString(Object myNotString) { - - this.myNotString = myNotString; - return this; - } +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; - /** - * Get myNotString - * @return myNotString - **/ - @javax.annotation.Nullable +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; - public Object getMyNotString() { - return myNotString; - } +import test.test.runtime.JSON; +/** + * AllOfInlineAndRefsAllOf1 + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AllOfInlineAndRefsAllOf1 { + public static final String SERIALIZED_NAME_E = "e"; + @SerializedName(SERIALIZED_NAME_E) + private String e; - public void setMyNotString(Object myNotString) { - this.myNotString = myNotString; + public AllOfInlineAndRefsAllOf1() { } - - public DataTypes200Response myAdditionalProperties(Map> myAdditionalProperties) { + public AllOfInlineAndRefsAllOf1 e(String e) { - this.myAdditionalProperties = myAdditionalProperties; - return this; - } - - public DataTypes200Response putMyAdditionalPropertiesItem(String key, List myAdditionalPropertiesItem) { - if (this.myAdditionalProperties == null) { - this.myAdditionalProperties = new HashMap<>(); - } - this.myAdditionalProperties.put(key, myAdditionalPropertiesItem); + this.e = e; return this; } /** - * Get myAdditionalProperties - * @return myAdditionalProperties + * Get e + * @return e **/ @javax.annotation.Nullable - public Map> getMyAdditionalProperties() { - return myAdditionalProperties; + public String getE() { + return e; } - public void setMyAdditionalProperties(Map> myAdditionalProperties) { - this.myAdditionalProperties = myAdditionalProperties; + public void setE(String e) { + this.e = e; } @@ -12458,73 +12913,20 @@ public class DataTypes200Response { if (o == null || getClass() != o.getClass()) { return false; } - DataTypes200Response dataTypes200Response = (DataTypes200Response) o; - return Objects.equals(this.myInt, dataTypes200Response.myInt) && - Objects.equals(this.myString, dataTypes200Response.myString) && - Objects.equals(this.myStringLength, dataTypes200Response.myStringLength) && - Objects.equals(this.myLongMinStringLength, dataTypes200Response.myLongMinStringLength) && - Objects.equals(this.myBool, dataTypes200Response.myBool) && - Objects.equals(this.myNumber, dataTypes200Response.myNumber) && - Objects.equals(this.myDateArray, dataTypes200Response.myDateArray) && - Objects.equals(this.myEmail, dataTypes200Response.myEmail) && - Objects.equals(this.myUrl, dataTypes200Response.myUrl) && - Objects.equals(this.myHostname, dataTypes200Response.myHostname) && - Objects.equals(this.myIpv4, dataTypes200Response.myIpv4) && - Objects.equals(this.myIpv6, dataTypes200Response.myIpv6) && - Objects.equals(this.myUuid, dataTypes200Response.myUuid) && - Arrays.equals(this.myByte, dataTypes200Response.myByte) && - Objects.equals(this.myDateTime, dataTypes200Response.myDateTime) && - Objects.equals(this.myRegexPattern, dataTypes200Response.myRegexPattern) && - Objects.equals(this.myOneOf, dataTypes200Response.myOneOf) && - Objects.equals(this.myAnyOf, dataTypes200Response.myAnyOf) && - Objects.equals(this.myAllOf, dataTypes200Response.myAllOf) && - Objects.equals(this.myNot, dataTypes200Response.myNot) && - Objects.equals(this.myNotString, dataTypes200Response.myNotString) && - Objects.equals(this.myAdditionalProperties, dataTypes200Response.myAdditionalProperties); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + AllOfInlineAndRefsAllOf1 allOfInlineAndRefsAllOf1 = (AllOfInlineAndRefsAllOf1) o; + return Objects.equals(this.e, allOfInlineAndRefsAllOf1.e); } @Override public int hashCode() { - return Objects.hash(myInt, myString, myStringLength, myLongMinStringLength, myBool, myNumber, myDateArray, myEmail, myUrl, myHostname, myIpv4, myIpv6, myUuid, Arrays.hashCode(myByte), myDateTime, myRegexPattern, myOneOf, myAnyOf, myAllOf, myNot, myNotString, myAdditionalProperties); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; - } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + return Objects.hash(e); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class DataTypes200Response {\\n"); - sb.append(" myInt: ").append(toIndentedString(myInt)).append("\\n"); - sb.append(" myString: ").append(toIndentedString(myString)).append("\\n"); - sb.append(" myStringLength: ").append(toIndentedString(myStringLength)).append("\\n"); - sb.append(" myLongMinStringLength: ").append(toIndentedString(myLongMinStringLength)).append("\\n"); - sb.append(" myBool: ").append(toIndentedString(myBool)).append("\\n"); - sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\\n"); - sb.append(" myDateArray: ").append(toIndentedString(myDateArray)).append("\\n"); - sb.append(" myEmail: ").append(toIndentedString(myEmail)).append("\\n"); - sb.append(" myUrl: ").append(toIndentedString(myUrl)).append("\\n"); - sb.append(" myHostname: ").append(toIndentedString(myHostname)).append("\\n"); - sb.append(" myIpv4: ").append(toIndentedString(myIpv4)).append("\\n"); - sb.append(" myIpv6: ").append(toIndentedString(myIpv6)).append("\\n"); - sb.append(" myUuid: ").append(toIndentedString(myUuid)).append("\\n"); - sb.append(" myByte: ").append(toIndentedString(myByte)).append("\\n"); - sb.append(" myDateTime: ").append(toIndentedString(myDateTime)).append("\\n"); - sb.append(" myRegexPattern: ").append(toIndentedString(myRegexPattern)).append("\\n"); - sb.append(" myOneOf: ").append(toIndentedString(myOneOf)).append("\\n"); - sb.append(" myAnyOf: ").append(toIndentedString(myAnyOf)).append("\\n"); - sb.append(" myAllOf: ").append(toIndentedString(myAllOf)).append("\\n"); - sb.append(" myNot: ").append(toIndentedString(myNot)).append("\\n"); - sb.append(" myNotString: ").append(toIndentedString(myNotString)).append("\\n"); - sb.append(" myAdditionalProperties: ").append(toIndentedString(myAdditionalProperties)).append("\\n"); + sb.append("class AllOfInlineAndRefsAllOf1 {\\n"); + sb.append(" e: ").append(toIndentedString(e)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -12547,28 +12949,7 @@ public class DataTypes200Response { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("myInt"); - openapiFields.add("myString"); - openapiFields.add("myStringLength"); - openapiFields.add("myLongMinStringLength"); - openapiFields.add("myBool"); - openapiFields.add("myNumber"); - openapiFields.add("myDateArray"); - openapiFields.add("myEmail"); - openapiFields.add("myUrl"); - openapiFields.add("myHostname"); - openapiFields.add("myIpv4"); - openapiFields.add("myIpv6"); - openapiFields.add("myUuid"); - openapiFields.add("myByte"); - openapiFields.add("myDateTime"); - openapiFields.add("myRegexPattern"); - openapiFields.add("myOneOf"); - openapiFields.add("myAnyOf"); - openapiFields.add("myAllOf"); - openapiFields.add("myNot"); - openapiFields.add("myNotString"); - openapiFields.add("myAdditionalProperties"); + openapiFields.add("e"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); @@ -12578,67 +12959,24 @@ public class DataTypes200Response { * 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 DataTypes200Response + * @throws IOException if the JSON Object is invalid with respect to AllOfInlineAndRefsAllOf1 */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!DataTypes200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200Response is not found in the empty JSON string", DataTypes200Response.openapiRequiredFields.toString())); + if (!AllOfInlineAndRefsAllOf1.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AllOfInlineAndRefsAllOf1 is not found in the empty JSON string", AllOfInlineAndRefsAllOf1.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!DataTypes200Response.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200Response\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!AllOfInlineAndRefsAllOf1.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AllOfInlineAndRefsAllOf1\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if ((jsonObj.get("myString") != null && !jsonObj.get("myString").isJsonNull()) && !jsonObj.get("myString").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myString\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myString").toString())); - } - if ((jsonObj.get("myStringLength") != null && !jsonObj.get("myStringLength").isJsonNull()) && !jsonObj.get("myStringLength").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myStringLength\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myStringLength").toString())); - } - if ((jsonObj.get("myLongMinStringLength") != null && !jsonObj.get("myLongMinStringLength").isJsonNull()) && !jsonObj.get("myLongMinStringLength").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myLongMinStringLength\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myLongMinStringLength").toString())); - } - // ensure the optional json data is an array if present - if (jsonObj.get("myDateArray") != null && !jsonObj.get("myDateArray").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field \`myDateArray\` to be an array in the JSON string but got \`%s\`", jsonObj.get("myDateArray").toString())); - } - if ((jsonObj.get("myEmail") != null && !jsonObj.get("myEmail").isJsonNull()) && !jsonObj.get("myEmail").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myEmail\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myEmail").toString())); - } - if ((jsonObj.get("myUrl") != null && !jsonObj.get("myUrl").isJsonNull()) && !jsonObj.get("myUrl").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myUrl\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myUrl").toString())); - } - if ((jsonObj.get("myHostname") != null && !jsonObj.get("myHostname").isJsonNull()) && !jsonObj.get("myHostname").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myHostname\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myHostname").toString())); - } - if ((jsonObj.get("myIpv4") != null && !jsonObj.get("myIpv4").isJsonNull()) && !jsonObj.get("myIpv4").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myIpv4\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myIpv4").toString())); - } - if ((jsonObj.get("myIpv6") != null && !jsonObj.get("myIpv6").isJsonNull()) && !jsonObj.get("myIpv6").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myIpv6\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myIpv6").toString())); - } - if ((jsonObj.get("myUuid") != null && !jsonObj.get("myUuid").isJsonNull()) && !jsonObj.get("myUuid").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myUuid\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myUuid").toString())); - } - if ((jsonObj.get("myRegexPattern") != null && !jsonObj.get("myRegexPattern").isJsonNull()) && !jsonObj.get("myRegexPattern").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`myRegexPattern\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myRegexPattern").toString())); - } - // validate the optional field \`myOneOf\` - if (jsonObj.get("myOneOf") != null && !jsonObj.get("myOneOf").isJsonNull()) { - DataTypes200ResponseMyOneOf.validateJsonObject(jsonObj.getAsJsonObject("myOneOf")); - } - // validate the optional field \`myAnyOf\` - if (jsonObj.get("myAnyOf") != null && !jsonObj.get("myAnyOf").isJsonNull()) { - DataTypes200ResponseMyAnyOf.validateJsonObject(jsonObj.getAsJsonObject("myAnyOf")); - } - // validate the optional field \`myAllOf\` - if (jsonObj.get("myAllOf") != null && !jsonObj.get("myAllOf").isJsonNull()) { - DataTypes200ResponseMyAllOf.validateJsonObject(jsonObj.getAsJsonObject("myAllOf")); + if ((jsonObj.get("e") != null && !jsonObj.get("e").isJsonNull()) && !jsonObj.get("e").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`e\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("e").toString())); } } @@ -12646,22 +12984,22 @@ public class DataTypes200Response { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!DataTypes200Response.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DataTypes200Response' and its subtypes + if (!AllOfInlineAndRefsAllOf1.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfInlineAndRefsAllOf1' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200Response.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfInlineAndRefsAllOf1.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, DataTypes200Response value) throws IOException { + public void write(JsonWriter out, AllOfInlineAndRefsAllOf1 value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public DataTypes200Response read(JsonReader in) throws IOException { + public AllOfInlineAndRefsAllOf1 read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -12672,18 +13010,18 @@ public class DataTypes200Response { } /** - * Create an instance of DataTypes200Response given an JSON string + * Create an instance of AllOfInlineAndRefsAllOf1 given an JSON string * * @param jsonString JSON string - * @return An instance of DataTypes200Response - * @throws IOException if the JSON string is invalid with respect to DataTypes200Response + * @return An instance of AllOfInlineAndRefsAllOf1 + * @throws IOException if the JSON string is invalid with respect to AllOfInlineAndRefsAllOf1 */ - public static DataTypes200Response fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DataTypes200Response.class); + public static AllOfInlineAndRefsAllOf1 fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfInlineAndRefsAllOf1.class); } /** - * Convert an instance of DataTypes200Response to an JSON string + * Convert an instance of AllOfInlineAndRefsAllOf1 to an JSON string * * @return JSON string */ @@ -12693,8 +13031,8 @@ public class DataTypes200Response { } ", - "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOf.java": "/* - * Data Types + "src/main/java/test/test/runtime/model/AllOfRefs.java": "/* + * composite models * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 @@ -12739,63 +13077,89 @@ import java.util.Set; import test.test.runtime.JSON; /** - * DataTypes200ResponseMyAllOf + * AllOfRefs */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DataTypes200ResponseMyAllOf { - public static final String SERIALIZED_NAME_FIRST = "first"; - @SerializedName(SERIALIZED_NAME_FIRST) - private String first; +public class AllOfRefs { + public static final String SERIALIZED_NAME_A = "a"; + @SerializedName(SERIALIZED_NAME_A) + private String a; - public static final String SERIALIZED_NAME_SECOND = "second"; - @SerializedName(SERIALIZED_NAME_SECOND) - private String second; + public static final String SERIALIZED_NAME_B = "b"; + @SerializedName(SERIALIZED_NAME_B) + private String b; - public DataTypes200ResponseMyAllOf() { + public static final String SERIALIZED_NAME_C = "c"; + @SerializedName(SERIALIZED_NAME_C) + private String c; + + public AllOfRefs() { } - public DataTypes200ResponseMyAllOf first(String first) { + public AllOfRefs a(String a) { - this.first = first; + this.a = a; return this; } /** - * Get first - * @return first + * Get a + * @return a **/ - @javax.annotation.Nullable + @javax.annotation.Nonnull - public String getFirst() { - return first; + public String getA() { + return a; } - public void setFirst(String first) { - this.first = first; + public void setA(String a) { + this.a = a; } - public DataTypes200ResponseMyAllOf second(String second) { + public AllOfRefs b(String b) { - this.second = second; + this.b = b; return this; } /** - * Get second - * @return second + * Get b + * @return b **/ - @javax.annotation.Nullable + @javax.annotation.Nonnull - public String getSecond() { - return second; + public String getB() { + return b; } - public void setSecond(String second) { - this.second = second; + public void setB(String b) { + this.b = b; + } + + + public AllOfRefs c(String c) { + + this.c = c; + return this; + } + + /** + * Get c + * @return c + **/ + @javax.annotation.Nonnull + + public String getC() { + return c; + } + + + public void setC(String c) { + this.c = c; } @@ -12808,22 +13172,24 @@ public class DataTypes200ResponseMyAllOf { if (o == null || getClass() != o.getClass()) { return false; } - DataTypes200ResponseMyAllOf dataTypes200ResponseMyAllOf = (DataTypes200ResponseMyAllOf) o; - return Objects.equals(this.first, dataTypes200ResponseMyAllOf.first) && - Objects.equals(this.second, dataTypes200ResponseMyAllOf.second); + AllOfRefs allOfRefs = (AllOfRefs) o; + return Objects.equals(this.a, allOfRefs.a) && + Objects.equals(this.b, allOfRefs.b) && + Objects.equals(this.c, allOfRefs.c); } @Override public int hashCode() { - return Objects.hash(first, second); + return Objects.hash(a, b, c); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class DataTypes200ResponseMyAllOf {\\n"); - sb.append(" first: ").append(toIndentedString(first)).append("\\n"); - sb.append(" second: ").append(toIndentedString(second)).append("\\n"); + sb.append("class AllOfRefs {\\n"); + sb.append(" a: ").append(toIndentedString(a)).append("\\n"); + sb.append(" b: ").append(toIndentedString(b)).append("\\n"); + sb.append(" c: ").append(toIndentedString(c)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -12846,38 +13212,52 @@ public class DataTypes200ResponseMyAllOf { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("first"); - openapiFields.add("second"); + openapiFields.add("a"); + openapiFields.add("b"); + openapiFields.add("c"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("a"); + openapiRequiredFields.add("b"); + openapiRequiredFields.add("c"); } /** * 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 DataTypes200ResponseMyAllOf + * @throws IOException if the JSON Object is invalid with respect to AllOfRefs */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!DataTypes200ResponseMyAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyAllOf is not found in the empty JSON string", DataTypes200ResponseMyAllOf.openapiRequiredFields.toString())); + if (!AllOfRefs.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AllOfRefs is not found in the empty JSON string", AllOfRefs.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!DataTypes200ResponseMyAllOf.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyAllOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!AllOfRefs.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AllOfRefs\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if ((jsonObj.get("first") != null && !jsonObj.get("first").isJsonNull()) && !jsonObj.get("first").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`first\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("first").toString())); + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AllOfRefs.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("second") != null && !jsonObj.get("second").isJsonNull()) && !jsonObj.get("second").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`second\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("second").toString())); + if (!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())); + } + if (!jsonObj.get("b").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`b\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("b").toString())); + } + if (!jsonObj.get("c").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`c\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("c").toString())); } } @@ -12885,44 +13265,11814 @@ public class DataTypes200ResponseMyAllOf { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!DataTypes200ResponseMyAllOf.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DataTypes200ResponseMyAllOf' and its subtypes + if (!AllOfRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfRefs' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyAllOf.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfRefs.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, DataTypes200ResponseMyAllOf value) throws IOException { + public void write(JsonWriter out, AllOfRefs value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public DataTypes200ResponseMyAllOf read(JsonReader in) throws IOException { + public AllOfRefs read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); } - }.nullSafe(); + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfRefs + * @throws IOException if the JSON string is invalid with respect to AllOfRefs + */ + public static AllOfRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfRefs.class); + } + + /** + * Convert an instance of AllOfRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/AnyOfInlineAndRefs.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.A; +import test.test.runtime.model.AllOfInlineAndRefsAllOf; +import test.test.runtime.model.AllOfInlineAndRefsAllOf1; +import test.test.runtime.model.B; +import test.test.runtime.model.C; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AnyOfInlineAndRefs extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AnyOfInlineAndRefs.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AnyOfInlineAndRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AnyOfInlineAndRefs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterA = gson.getDelegateAdapter(this, TypeToken.get(A.class)); + final TypeAdapter adapterAllOfInlineAndRefsAllOf = gson.getDelegateAdapter(this, TypeToken.get(AllOfInlineAndRefsAllOf.class)); + final TypeAdapter adapterAllOfInlineAndRefsAllOf1 = gson.getDelegateAdapter(this, TypeToken.get(AllOfInlineAndRefsAllOf1.class)); + final TypeAdapter adapterB = gson.getDelegateAdapter(this, TypeToken.get(B.class)); + final TypeAdapter adapterC = gson.getDelegateAdapter(this, TypeToken.get(C.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AnyOfInlineAndRefs value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`A\` + if (value.getActualInstance() instanceof A) { + JsonObject obj = adapterA.toJsonTree((A)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`AllOfInlineAndRefsAllOf\` + if (value.getActualInstance() instanceof AllOfInlineAndRefsAllOf) { + JsonObject obj = adapterAllOfInlineAndRefsAllOf.toJsonTree((AllOfInlineAndRefsAllOf)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`AllOfInlineAndRefsAllOf1\` + if (value.getActualInstance() instanceof AllOfInlineAndRefsAllOf1) { + JsonObject obj = adapterAllOfInlineAndRefsAllOf1.toJsonTree((AllOfInlineAndRefsAllOf1)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`B\` + if (value.getActualInstance() instanceof B) { + JsonObject obj = adapterB.toJsonTree((B)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`C\` + if (value.getActualInstance() instanceof C) { + JsonObject obj = adapterC.toJsonTree((C)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C"); + } + + @Override + public AnyOfInlineAndRefs read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + // deserialize A + try { + // validate the JSON object to see if any exception is thrown + A.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'A'"); + AnyOfInlineAndRefs ret = new AnyOfInlineAndRefs(); + ret.setActualInstance(adapterA.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'A'", e); + } + + // deserialize AllOfInlineAndRefsAllOf + try { + // validate the JSON object to see if any exception is thrown + AllOfInlineAndRefsAllOf.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'AllOfInlineAndRefsAllOf'"); + AnyOfInlineAndRefs ret = new AnyOfInlineAndRefs(); + ret.setActualInstance(adapterAllOfInlineAndRefsAllOf.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'AllOfInlineAndRefsAllOf'", e); + } + + // deserialize AllOfInlineAndRefsAllOf1 + try { + // validate the JSON object to see if any exception is thrown + AllOfInlineAndRefsAllOf1.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'AllOfInlineAndRefsAllOf1'"); + AnyOfInlineAndRefs ret = new AnyOfInlineAndRefs(); + ret.setActualInstance(adapterAllOfInlineAndRefsAllOf1.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'AllOfInlineAndRefsAllOf1'", e); + } + + // deserialize B + try { + // validate the JSON object to see if any exception is thrown + B.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'B'"); + AnyOfInlineAndRefs ret = new AnyOfInlineAndRefs(); + ret.setActualInstance(adapterB.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'B'", e); + } + + // deserialize C + try { + // validate the JSON object to see if any exception is thrown + C.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'C'"); + AnyOfInlineAndRefs ret = new AnyOfInlineAndRefs(); + ret.setActualInstance(adapterC.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'C'", e); + } + + + throw new IOException(String.format("Failed deserialization for AnyOfInlineAndRefs: no class matched. JSON: %s", jsonObject.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map schemas = new HashMap(); + + public AnyOfInlineAndRefs() { + super("anyOf", Boolean.FALSE); + } + + public AnyOfInlineAndRefs(A o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfInlineAndRefs(AllOfInlineAndRefsAllOf o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfInlineAndRefs(AllOfInlineAndRefsAllOf1 o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfInlineAndRefs(B o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfInlineAndRefs(C o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("A", new GenericType() { + }); + schemas.put("AllOfInlineAndRefsAllOf", new GenericType() { + }); + schemas.put("AllOfInlineAndRefsAllOf1", new GenericType() { + }); + schemas.put("B", new GenericType() { + }); + schemas.put("C", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return AnyOfInlineAndRefs.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof A) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof AllOfInlineAndRefsAllOf) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof AllOfInlineAndRefsAllOf1) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof B) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof C) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C"); + } + + /** + * Get the actual instance, which can be the following: + * A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C + * + * @return The actual instance (A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`A\`. If the actual instance is not \`A\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`A\` + * @throws ClassCastException if the instance is not \`A\` + */ + public A getA() throws ClassCastException { + return (A)super.getActualInstance(); + } + + /** + * Get the actual instance of \`AllOfInlineAndRefsAllOf\`. If the actual instance is not \`AllOfInlineAndRefsAllOf\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`AllOfInlineAndRefsAllOf\` + * @throws ClassCastException if the instance is not \`AllOfInlineAndRefsAllOf\` + */ + public AllOfInlineAndRefsAllOf getAllOfInlineAndRefsAllOf() throws ClassCastException { + return (AllOfInlineAndRefsAllOf)super.getActualInstance(); + } + + /** + * Get the actual instance of \`AllOfInlineAndRefsAllOf1\`. If the actual instance is not \`AllOfInlineAndRefsAllOf1\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`AllOfInlineAndRefsAllOf1\` + * @throws ClassCastException if the instance is not \`AllOfInlineAndRefsAllOf1\` + */ + public AllOfInlineAndRefsAllOf1 getAllOfInlineAndRefsAllOf1() throws ClassCastException { + return (AllOfInlineAndRefsAllOf1)super.getActualInstance(); + } + + /** + * Get the actual instance of \`B\`. If the actual instance is not \`B\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`B\` + * @throws ClassCastException if the instance is not \`B\` + */ + public B getB() throws ClassCastException { + return (B)super.getActualInstance(); + } + + /** + * Get the actual instance of \`C\`. If the actual instance is not \`C\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`C\` + * @throws ClassCastException if the instance is not \`C\` + */ + public C getC() throws ClassCastException { + return (C)super.getActualInstance(); + } + + + /** + * 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 AnyOfInlineAndRefs + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + // validate anyOf schemas one by one + int validCount = 0; + // validate the json string with A + try { + A.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with AllOfInlineAndRefsAllOf + try { + AllOfInlineAndRefsAllOf.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with AllOfInlineAndRefsAllOf1 + try { + AllOfInlineAndRefsAllOf1.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with B + try { + B.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with C + try { + C.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + if (validCount == 0) { + throw new IOException(String.format("The JSON string is invalid for AnyOfInlineAndRefs with anyOf schemas: A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C. JSON: %s", jsonObj.toString())); + } + } + + /** + * Create an instance of AnyOfInlineAndRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of AnyOfInlineAndRefs + * @throws IOException if the JSON string is invalid with respect to AnyOfInlineAndRefs + */ + public static AnyOfInlineAndRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AnyOfInlineAndRefs.class); + } + + /** + * Convert an instance of AnyOfInlineAndRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/AnyOfPrimitives.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AnyOfPrimitives extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AnyOfPrimitives.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AnyOfPrimitives.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AnyOfPrimitives' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AnyOfPrimitives value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`Integer\` + if (value.getActualInstance() instanceof Integer) { + JsonObject obj = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`String\` + if (value.getActualInstance() instanceof String) { + JsonObject obj = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Integer, String"); + } + + @Override + public AnyOfPrimitives read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + // deserialize Integer + try { + // validate the JSON object to see if any exception is thrown + Integer.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'Integer'"); + AnyOfPrimitives ret = new AnyOfPrimitives(); + ret.setActualInstance(adapterInteger.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Integer'", e); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + String.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'String'"); + AnyOfPrimitives ret = new AnyOfPrimitives(); + ret.setActualInstance(adapterString.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + + throw new IOException(String.format("Failed deserialization for AnyOfPrimitives: no class matched. JSON: %s", jsonObject.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map schemas = new HashMap(); + + public AnyOfPrimitives() { + super("anyOf", Boolean.FALSE); + } + + public AnyOfPrimitives(Integer o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfPrimitives(String o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Integer", new GenericType() { + }); + schemas.put("String", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return AnyOfPrimitives.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * Integer, String + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof Integer) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Integer, String"); + } + + /** + * Get the actual instance, which can be the following: + * Integer, String + * + * @return The actual instance (Integer, String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`Integer\`. If the actual instance is not \`Integer\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`Integer\` + * @throws ClassCastException if the instance is not \`Integer\` + */ + public Integer getInteger() throws ClassCastException { + return (Integer)super.getActualInstance(); + } + + /** + * Get the actual instance of \`String\`. If the actual instance is not \`String\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`String\` + * @throws ClassCastException if the instance is not \`String\` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + + /** + * 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 AnyOfPrimitives + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + // validate anyOf schemas one by one + int validCount = 0; + // validate the json string with Integer + try { + Integer.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with String + try { + String.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + if (validCount == 0) { + throw new IOException(String.format("The JSON string is invalid for AnyOfPrimitives with anyOf schemas: Integer, String. JSON: %s", jsonObj.toString())); + } + } + + /** + * Create an instance of AnyOfPrimitives given an JSON string + * + * @param jsonString JSON string + * @return An instance of AnyOfPrimitives + * @throws IOException if the JSON string is invalid with respect to AnyOfPrimitives + */ + public static AnyOfPrimitives fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AnyOfPrimitives.class); + } + + /** + * Convert an instance of AnyOfPrimitives to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/AnyOfPrimitivesAndRefs.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.A; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AnyOfPrimitivesAndRefs extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AnyOfPrimitivesAndRefs.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AnyOfPrimitivesAndRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AnyOfPrimitivesAndRefs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterA = gson.getDelegateAdapter(this, TypeToken.get(A.class)); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AnyOfPrimitivesAndRefs value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`A\` + if (value.getActualInstance() instanceof A) { + JsonObject obj = adapterA.toJsonTree((A)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`String\` + if (value.getActualInstance() instanceof String) { + JsonObject obj = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: A, String"); + } + + @Override + public AnyOfPrimitivesAndRefs read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + // deserialize A + try { + // validate the JSON object to see if any exception is thrown + A.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'A'"); + AnyOfPrimitivesAndRefs ret = new AnyOfPrimitivesAndRefs(); + ret.setActualInstance(adapterA.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'A'", e); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + String.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'String'"); + AnyOfPrimitivesAndRefs ret = new AnyOfPrimitivesAndRefs(); + ret.setActualInstance(adapterString.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + + throw new IOException(String.format("Failed deserialization for AnyOfPrimitivesAndRefs: no class matched. JSON: %s", jsonObject.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map schemas = new HashMap(); + + public AnyOfPrimitivesAndRefs() { + super("anyOf", Boolean.FALSE); + } + + public AnyOfPrimitivesAndRefs(A o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfPrimitivesAndRefs(String o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("A", new GenericType() { + }); + schemas.put("String", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return AnyOfPrimitivesAndRefs.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * A, String + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof A) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be A, String"); + } + + /** + * Get the actual instance, which can be the following: + * A, String + * + * @return The actual instance (A, String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`A\`. If the actual instance is not \`A\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`A\` + * @throws ClassCastException if the instance is not \`A\` + */ + public A getA() throws ClassCastException { + return (A)super.getActualInstance(); + } + + /** + * Get the actual instance of \`String\`. If the actual instance is not \`String\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`String\` + * @throws ClassCastException if the instance is not \`String\` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + + /** + * 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 AnyOfPrimitivesAndRefs + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + // validate anyOf schemas one by one + int validCount = 0; + // validate the json string with A + try { + A.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with String + try { + String.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + if (validCount == 0) { + throw new IOException(String.format("The JSON string is invalid for AnyOfPrimitivesAndRefs with anyOf schemas: A, String. JSON: %s", jsonObj.toString())); + } + } + + /** + * Create an instance of AnyOfPrimitivesAndRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of AnyOfPrimitivesAndRefs + * @throws IOException if the JSON string is invalid with respect to AnyOfPrimitivesAndRefs + */ + public static AnyOfPrimitivesAndRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AnyOfPrimitivesAndRefs.class); + } + + /** + * Convert an instance of AnyOfPrimitivesAndRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/AnyOfRefs.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.A; +import test.test.runtime.model.B; +import test.test.runtime.model.C; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AnyOfRefs extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AnyOfRefs.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AnyOfRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AnyOfRefs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterA = gson.getDelegateAdapter(this, TypeToken.get(A.class)); + final TypeAdapter adapterB = gson.getDelegateAdapter(this, TypeToken.get(B.class)); + final TypeAdapter adapterC = gson.getDelegateAdapter(this, TypeToken.get(C.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AnyOfRefs value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`A\` + if (value.getActualInstance() instanceof A) { + JsonObject obj = adapterA.toJsonTree((A)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`B\` + if (value.getActualInstance() instanceof B) { + JsonObject obj = adapterB.toJsonTree((B)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`C\` + if (value.getActualInstance() instanceof C) { + JsonObject obj = adapterC.toJsonTree((C)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: A, B, C"); + } + + @Override + public AnyOfRefs read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + // deserialize A + try { + // validate the JSON object to see if any exception is thrown + A.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'A'"); + AnyOfRefs ret = new AnyOfRefs(); + ret.setActualInstance(adapterA.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'A'", e); + } + + // deserialize B + try { + // validate the JSON object to see if any exception is thrown + B.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'B'"); + AnyOfRefs ret = new AnyOfRefs(); + ret.setActualInstance(adapterB.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'B'", e); + } + + // deserialize C + try { + // validate the JSON object to see if any exception is thrown + C.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'C'"); + AnyOfRefs ret = new AnyOfRefs(); + ret.setActualInstance(adapterC.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'C'", e); + } + + + throw new IOException(String.format("Failed deserialization for AnyOfRefs: no class matched. JSON: %s", jsonObject.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map schemas = new HashMap(); + + public AnyOfRefs() { + super("anyOf", Boolean.FALSE); + } + + public AnyOfRefs(A o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfRefs(B o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AnyOfRefs(C o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("A", new GenericType() { + }); + schemas.put("B", new GenericType() { + }); + schemas.put("C", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return AnyOfRefs.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * A, B, C + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof A) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof B) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof C) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be A, B, C"); + } + + /** + * Get the actual instance, which can be the following: + * A, B, C + * + * @return The actual instance (A, B, C) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`A\`. If the actual instance is not \`A\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`A\` + * @throws ClassCastException if the instance is not \`A\` + */ + public A getA() throws ClassCastException { + return (A)super.getActualInstance(); + } + + /** + * Get the actual instance of \`B\`. If the actual instance is not \`B\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`B\` + * @throws ClassCastException if the instance is not \`B\` + */ + public B getB() throws ClassCastException { + return (B)super.getActualInstance(); + } + + /** + * Get the actual instance of \`C\`. If the actual instance is not \`C\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`C\` + * @throws ClassCastException if the instance is not \`C\` + */ + public C getC() throws ClassCastException { + return (C)super.getActualInstance(); + } + + + /** + * 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 AnyOfRefs + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + // validate anyOf schemas one by one + int validCount = 0; + // validate the json string with A + try { + A.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with B + try { + B.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with C + try { + C.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + if (validCount == 0) { + throw new IOException(String.format("The JSON string is invalid for AnyOfRefs with anyOf schemas: A, B, C. JSON: %s", jsonObj.toString())); + } + } + + /** + * Create an instance of AnyOfRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of AnyOfRefs + * @throws IOException if the JSON string is invalid with respect to AnyOfRefs + */ + public static AnyOfRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AnyOfRefs.class); + } + + /** + * Convert an instance of AnyOfRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/B.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * B + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class B { + public static final String SERIALIZED_NAME_B = "b"; + @SerializedName(SERIALIZED_NAME_B) + private String b; + + public B() { + } + + public B b(String b) { + + this.b = b; + return this; + } + + /** + * Get b + * @return b + **/ + @javax.annotation.Nonnull + + public String getB() { + return b; + } + + + public void setB(String b) { + this.b = b; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + B B = (B) o; + return Objects.equals(this.b, B.b); + } + + @Override + public int hashCode() { + return Objects.hash(b); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class B {\\n"); + sb.append(" b: ").append(toIndentedString(b)).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("b"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("b"); + } + + /** + * 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 B + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!B.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in B is not found in the empty JSON string", B.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!B.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`B\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : B.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("b").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`b\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("b").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!B.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'B' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(B.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, B value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public B read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of B given an JSON string + * + * @param jsonString JSON string + * @return An instance of B + * @throws IOException if the JSON string is invalid with respect to B + */ + public static B fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, B.class); + } + + /** + * Convert an instance of B to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/C.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * C + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class C { + public static final String SERIALIZED_NAME_C = "c"; + @SerializedName(SERIALIZED_NAME_C) + private String c; + + public C() { + } + + public C c(String c) { + + this.c = c; + return this; + } + + /** + * Get c + * @return c + **/ + @javax.annotation.Nonnull + + public String getC() { + return c; + } + + + public void setC(String c) { + this.c = c; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + C C = (C) o; + return Objects.equals(this.c, C.c); + } + + @Override + public int hashCode() { + return Objects.hash(c); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class C {\\n"); + sb.append(" c: ").append(toIndentedString(c)).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("c"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("c"); + } + + /** + * 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 C + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!C.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in C is not found in the empty JSON string", C.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!C.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`C\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : C.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("c").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`c\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("c").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!C.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'C' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(C.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, C value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public C read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of C given an JSON string + * + * @param jsonString JSON string + * @return An instance of C + * @throws IOException if the JSON string is invalid with respect to C + */ + public static C fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, C.class); + } + + /** + * Convert an instance of C to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/OneOfInlineAndRefs.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.A; +import test.test.runtime.model.AllOfInlineAndRefsAllOf; +import test.test.runtime.model.AllOfInlineAndRefsAllOf1; +import test.test.runtime.model.B; +import test.test.runtime.model.C; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class OneOfInlineAndRefs extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(OneOfInlineAndRefs.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!OneOfInlineAndRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'OneOfInlineAndRefs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterA = gson.getDelegateAdapter(this, TypeToken.get(A.class)); + final TypeAdapter adapterAllOfInlineAndRefsAllOf = gson.getDelegateAdapter(this, TypeToken.get(AllOfInlineAndRefsAllOf.class)); + final TypeAdapter adapterAllOfInlineAndRefsAllOf1 = gson.getDelegateAdapter(this, TypeToken.get(AllOfInlineAndRefsAllOf1.class)); + final TypeAdapter adapterB = gson.getDelegateAdapter(this, TypeToken.get(B.class)); + final TypeAdapter adapterC = gson.getDelegateAdapter(this, TypeToken.get(C.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, OneOfInlineAndRefs value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`A\` + if (value.getActualInstance() instanceof A) { + JsonObject obj = adapterA.toJsonTree((A)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`AllOfInlineAndRefsAllOf\` + if (value.getActualInstance() instanceof AllOfInlineAndRefsAllOf) { + JsonObject obj = adapterAllOfInlineAndRefsAllOf.toJsonTree((AllOfInlineAndRefsAllOf)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`AllOfInlineAndRefsAllOf1\` + if (value.getActualInstance() instanceof AllOfInlineAndRefsAllOf1) { + JsonObject obj = adapterAllOfInlineAndRefsAllOf1.toJsonTree((AllOfInlineAndRefsAllOf1)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`B\` + if (value.getActualInstance() instanceof B) { + JsonObject obj = adapterB.toJsonTree((B)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`C\` + if (value.getActualInstance() instanceof C) { + JsonObject obj = adapterC.toJsonTree((C)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C"); + } + + @Override + public OneOfInlineAndRefs 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 A + try { + // validate the JSON object to see if any exception is thrown + A.validateJsonObject(jsonObject); + actualAdapter = adapterA; + match++; + log.log(Level.FINER, "Input data matches schema 'A'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for A failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'A'", e); + } + + // deserialize AllOfInlineAndRefsAllOf + try { + // validate the JSON object to see if any exception is thrown + AllOfInlineAndRefsAllOf.validateJsonObject(jsonObject); + actualAdapter = adapterAllOfInlineAndRefsAllOf; + match++; + log.log(Level.FINER, "Input data matches schema 'AllOfInlineAndRefsAllOf'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for AllOfInlineAndRefsAllOf failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'AllOfInlineAndRefsAllOf'", e); + } + + // deserialize AllOfInlineAndRefsAllOf1 + try { + // validate the JSON object to see if any exception is thrown + AllOfInlineAndRefsAllOf1.validateJsonObject(jsonObject); + actualAdapter = adapterAllOfInlineAndRefsAllOf1; + match++; + log.log(Level.FINER, "Input data matches schema 'AllOfInlineAndRefsAllOf1'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for AllOfInlineAndRefsAllOf1 failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'AllOfInlineAndRefsAllOf1'", e); + } + + // deserialize B + try { + // validate the JSON object to see if any exception is thrown + B.validateJsonObject(jsonObject); + actualAdapter = adapterB; + match++; + log.log(Level.FINER, "Input data matches schema 'B'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for B failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'B'", e); + } + + // deserialize C + try { + // validate the JSON object to see if any exception is thrown + C.validateJsonObject(jsonObject); + actualAdapter = adapterC; + match++; + log.log(Level.FINER, "Input data matches schema 'C'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for C failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'C'", e); + } + + if (match == 1) { + OneOfInlineAndRefs ret = new OneOfInlineAndRefs(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for OneOfInlineAndRefs: %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 OneOfInlineAndRefs() { + super("oneOf", Boolean.FALSE); + } + + public OneOfInlineAndRefs(A o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfInlineAndRefs(AllOfInlineAndRefsAllOf o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfInlineAndRefs(AllOfInlineAndRefsAllOf1 o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfInlineAndRefs(B o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfInlineAndRefs(C o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("A", new GenericType() { + }); + schemas.put("AllOfInlineAndRefsAllOf", new GenericType() { + }); + schemas.put("AllOfInlineAndRefsAllOf1", new GenericType() { + }); + schemas.put("B", new GenericType() { + }); + schemas.put("C", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return OneOfInlineAndRefs.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C + * + * 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 A) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof AllOfInlineAndRefsAllOf) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof AllOfInlineAndRefsAllOf1) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof B) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof C) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C"); + } + + /** + * Get the actual instance, which can be the following: + * A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C + * + * @return The actual instance (A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`A\`. If the actual instance is not \`A\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`A\` + * @throws ClassCastException if the instance is not \`A\` + */ + public A getA() throws ClassCastException { + return (A)super.getActualInstance(); + } + + /** + * Get the actual instance of \`AllOfInlineAndRefsAllOf\`. If the actual instance is not \`AllOfInlineAndRefsAllOf\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`AllOfInlineAndRefsAllOf\` + * @throws ClassCastException if the instance is not \`AllOfInlineAndRefsAllOf\` + */ + public AllOfInlineAndRefsAllOf getAllOfInlineAndRefsAllOf() throws ClassCastException { + return (AllOfInlineAndRefsAllOf)super.getActualInstance(); + } + + /** + * Get the actual instance of \`AllOfInlineAndRefsAllOf1\`. If the actual instance is not \`AllOfInlineAndRefsAllOf1\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`AllOfInlineAndRefsAllOf1\` + * @throws ClassCastException if the instance is not \`AllOfInlineAndRefsAllOf1\` + */ + public AllOfInlineAndRefsAllOf1 getAllOfInlineAndRefsAllOf1() throws ClassCastException { + return (AllOfInlineAndRefsAllOf1)super.getActualInstance(); + } + + /** + * Get the actual instance of \`B\`. If the actual instance is not \`B\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`B\` + * @throws ClassCastException if the instance is not \`B\` + */ + public B getB() throws ClassCastException { + return (B)super.getActualInstance(); + } + + /** + * Get the actual instance of \`C\`. If the actual instance is not \`C\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`C\` + * @throws ClassCastException if the instance is not \`C\` + */ + public C getC() throws ClassCastException { + return (C)super.getActualInstance(); + } + + + /** + * 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 OneOfInlineAndRefs + */ + 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 A + try { + A.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for A failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with AllOfInlineAndRefsAllOf + try { + AllOfInlineAndRefsAllOf.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for AllOfInlineAndRefsAllOf failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with AllOfInlineAndRefsAllOf1 + try { + AllOfInlineAndRefsAllOf1.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for AllOfInlineAndRefsAllOf1 failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with B + try { + B.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for B failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with C + try { + C.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for C failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for OneOfInlineAndRefs with oneOf schemas: A, AllOfInlineAndRefsAllOf, AllOfInlineAndRefsAllOf1, B, C. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString())); + } + } + + /** + * Create an instance of OneOfInlineAndRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of OneOfInlineAndRefs + * @throws IOException if the JSON string is invalid with respect to OneOfInlineAndRefs + */ + public static OneOfInlineAndRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, OneOfInlineAndRefs.class); + } + + /** + * Convert an instance of OneOfInlineAndRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/OneOfPrimitives.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class OneOfPrimitives extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(OneOfPrimitives.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!OneOfPrimitives.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'OneOfPrimitives' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, OneOfPrimitives value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`Integer\` + if (value.getActualInstance() instanceof Integer) { + JsonObject obj = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`String\` + if (value.getActualInstance() instanceof String) { + JsonObject obj = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Integer, String"); + } + + @Override + public OneOfPrimitives 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 Integer + try { + // validate the JSON object to see if any exception is thrown + Integer.validateJsonObject(jsonObject); + actualAdapter = adapterInteger; + match++; + log.log(Level.FINER, "Input data matches schema 'Integer'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Integer'", e); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + String.validateJsonObject(jsonObject); + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + if (match == 1) { + OneOfPrimitives ret = new OneOfPrimitives(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for OneOfPrimitives: %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 OneOfPrimitives() { + super("oneOf", Boolean.FALSE); + } + + public OneOfPrimitives(Integer o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfPrimitives(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Integer", new GenericType() { + }); + schemas.put("String", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return OneOfPrimitives.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Integer, String + * + * 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 Integer) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Integer, String"); + } + + /** + * Get the actual instance, which can be the following: + * Integer, String + * + * @return The actual instance (Integer, String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`Integer\`. If the actual instance is not \`Integer\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`Integer\` + * @throws ClassCastException if the instance is not \`Integer\` + */ + public Integer getInteger() throws ClassCastException { + return (Integer)super.getActualInstance(); + } + + /** + * Get the actual instance of \`String\`. If the actual instance is not \`String\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`String\` + * @throws ClassCastException if the instance is not \`String\` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + + /** + * 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 OneOfPrimitives + */ + 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 Integer + try { + Integer.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for Integer failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with String + try { + String.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for String failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for OneOfPrimitives with oneOf schemas: Integer, String. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString())); + } + } + + /** + * Create an instance of OneOfPrimitives given an JSON string + * + * @param jsonString JSON string + * @return An instance of OneOfPrimitives + * @throws IOException if the JSON string is invalid with respect to OneOfPrimitives + */ + public static OneOfPrimitives fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, OneOfPrimitives.class); + } + + /** + * Convert an instance of OneOfPrimitives to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/OneOfPrimitivesAndRefs.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.A; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class OneOfPrimitivesAndRefs extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(OneOfPrimitivesAndRefs.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!OneOfPrimitivesAndRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'OneOfPrimitivesAndRefs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterA = gson.getDelegateAdapter(this, TypeToken.get(A.class)); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, OneOfPrimitivesAndRefs value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`A\` + if (value.getActualInstance() instanceof A) { + JsonObject obj = adapterA.toJsonTree((A)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`String\` + if (value.getActualInstance() instanceof String) { + JsonObject obj = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: A, String"); + } + + @Override + public OneOfPrimitivesAndRefs 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 A + try { + // validate the JSON object to see if any exception is thrown + A.validateJsonObject(jsonObject); + actualAdapter = adapterA; + match++; + log.log(Level.FINER, "Input data matches schema 'A'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for A failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'A'", e); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + String.validateJsonObject(jsonObject); + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + if (match == 1) { + OneOfPrimitivesAndRefs ret = new OneOfPrimitivesAndRefs(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for OneOfPrimitivesAndRefs: %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 OneOfPrimitivesAndRefs() { + super("oneOf", Boolean.FALSE); + } + + public OneOfPrimitivesAndRefs(A o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfPrimitivesAndRefs(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("A", new GenericType() { + }); + schemas.put("String", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return OneOfPrimitivesAndRefs.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * A, String + * + * 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 A) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be A, String"); + } + + /** + * Get the actual instance, which can be the following: + * A, String + * + * @return The actual instance (A, String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`A\`. If the actual instance is not \`A\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`A\` + * @throws ClassCastException if the instance is not \`A\` + */ + public A getA() throws ClassCastException { + return (A)super.getActualInstance(); + } + + /** + * Get the actual instance of \`String\`. If the actual instance is not \`String\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`String\` + * @throws ClassCastException if the instance is not \`String\` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + + /** + * 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 OneOfPrimitivesAndRefs + */ + 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 A + try { + A.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for A failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with String + try { + String.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for String failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for OneOfPrimitivesAndRefs with oneOf schemas: A, String. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString())); + } + } + + /** + * Create an instance of OneOfPrimitivesAndRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of OneOfPrimitivesAndRefs + * @throws IOException if the JSON string is invalid with respect to OneOfPrimitivesAndRefs + */ + public static OneOfPrimitivesAndRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, OneOfPrimitivesAndRefs.class); + } + + /** + * Convert an instance of OneOfPrimitivesAndRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/OneOfRefs.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.A; +import test.test.runtime.model.B; +import test.test.runtime.model.C; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class OneOfRefs extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(OneOfRefs.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!OneOfRefs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'OneOfRefs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterA = gson.getDelegateAdapter(this, TypeToken.get(A.class)); + final TypeAdapter adapterB = gson.getDelegateAdapter(this, TypeToken.get(B.class)); + final TypeAdapter adapterC = gson.getDelegateAdapter(this, TypeToken.get(C.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, OneOfRefs value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`A\` + if (value.getActualInstance() instanceof A) { + JsonObject obj = adapterA.toJsonTree((A)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`B\` + if (value.getActualInstance() instanceof B) { + JsonObject obj = adapterB.toJsonTree((B)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`C\` + if (value.getActualInstance() instanceof C) { + JsonObject obj = adapterC.toJsonTree((C)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: A, B, C"); + } + + @Override + public OneOfRefs 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 A + try { + // validate the JSON object to see if any exception is thrown + A.validateJsonObject(jsonObject); + actualAdapter = adapterA; + match++; + log.log(Level.FINER, "Input data matches schema 'A'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for A failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'A'", e); + } + + // deserialize B + try { + // validate the JSON object to see if any exception is thrown + B.validateJsonObject(jsonObject); + actualAdapter = adapterB; + match++; + log.log(Level.FINER, "Input data matches schema 'B'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for B failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'B'", e); + } + + // deserialize C + try { + // validate the JSON object to see if any exception is thrown + C.validateJsonObject(jsonObject); + actualAdapter = adapterC; + match++; + log.log(Level.FINER, "Input data matches schema 'C'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for C failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'C'", e); + } + + if (match == 1) { + OneOfRefs ret = new OneOfRefs(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for OneOfRefs: %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 OneOfRefs() { + super("oneOf", Boolean.FALSE); + } + + public OneOfRefs(A o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfRefs(B o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public OneOfRefs(C o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("A", new GenericType() { + }); + schemas.put("B", new GenericType() { + }); + schemas.put("C", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return OneOfRefs.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * A, B, C + * + * 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 A) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof B) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof C) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be A, B, C"); + } + + /** + * Get the actual instance, which can be the following: + * A, B, C + * + * @return The actual instance (A, B, C) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`A\`. If the actual instance is not \`A\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`A\` + * @throws ClassCastException if the instance is not \`A\` + */ + public A getA() throws ClassCastException { + return (A)super.getActualInstance(); + } + + /** + * Get the actual instance of \`B\`. If the actual instance is not \`B\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`B\` + * @throws ClassCastException if the instance is not \`B\` + */ + public B getB() throws ClassCastException { + return (B)super.getActualInstance(); + } + + /** + * Get the actual instance of \`C\`. If the actual instance is not \`C\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`C\` + * @throws ClassCastException if the instance is not \`C\` + */ + public C getC() throws ClassCastException { + return (C)super.getActualInstance(); + } + + + /** + * 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 OneOfRefs + */ + 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 A + try { + A.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for A failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with B + try { + B.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for B failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with C + try { + C.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for C failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for OneOfRefs with oneOf schemas: A, B, C. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString())); + } + } + + /** + * Create an instance of OneOfRefs given an JSON string + * + * @param jsonString JSON string + * @return An instance of OneOfRefs + * @throws IOException if the JSON string is invalid with respect to OneOfRefs + */ + public static OneOfRefs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, OneOfRefs.class); + } + + /** + * Convert an instance of OneOfRefs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/Wrapper.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.WrapperAllOf; +import test.test.runtime.model.WrapperAnyOf; +import test.test.runtime.model.WrapperOneOf; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * Wrapper + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Wrapper { + public static final String SERIALIZED_NAME_ALL_OF = "allOf"; + @SerializedName(SERIALIZED_NAME_ALL_OF) + private WrapperAllOf allOf; + + public static final String SERIALIZED_NAME_ANY_OF = "anyOf"; + @SerializedName(SERIALIZED_NAME_ANY_OF) + private WrapperAnyOf anyOf; + + public static final String SERIALIZED_NAME_ONE_OF = "oneOf"; + @SerializedName(SERIALIZED_NAME_ONE_OF) + private WrapperOneOf oneOf; + + public Wrapper() { + } + + public Wrapper allOf(WrapperAllOf allOf) { + + this.allOf = allOf; + return this; + } + + /** + * Get allOf + * @return allOf + **/ + @javax.annotation.Nullable + + public WrapperAllOf getAllOf() { + return allOf; + } + + + public void setAllOf(WrapperAllOf allOf) { + this.allOf = allOf; + } + + + public Wrapper anyOf(WrapperAnyOf anyOf) { + + this.anyOf = anyOf; + return this; + } + + /** + * Get anyOf + * @return anyOf + **/ + @javax.annotation.Nullable + + public WrapperAnyOf getAnyOf() { + return anyOf; + } + + + public void setAnyOf(WrapperAnyOf anyOf) { + this.anyOf = anyOf; + } + + + public Wrapper oneOf(WrapperOneOf oneOf) { + + this.oneOf = oneOf; + return this; + } + + /** + * Get oneOf + * @return oneOf + **/ + @javax.annotation.Nullable + + public WrapperOneOf getOneOf() { + return oneOf; + } + + + public void setOneOf(WrapperOneOf oneOf) { + this.oneOf = oneOf; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Wrapper wrapper = (Wrapper) o; + return Objects.equals(this.allOf, wrapper.allOf) && + Objects.equals(this.anyOf, wrapper.anyOf) && + Objects.equals(this.oneOf, wrapper.oneOf); + } + + @Override + public int hashCode() { + return Objects.hash(allOf, anyOf, oneOf); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Wrapper {\\n"); + sb.append(" allOf: ").append(toIndentedString(allOf)).append("\\n"); + sb.append(" anyOf: ").append(toIndentedString(anyOf)).append("\\n"); + sb.append(" oneOf: ").append(toIndentedString(oneOf)).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("allOf"); + openapiFields.add("anyOf"); + openapiFields.add("oneOf"); + + // 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 Wrapper + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!Wrapper.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in Wrapper is not found in the empty JSON string", Wrapper.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!Wrapper.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`Wrapper\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // validate the optional field \`allOf\` + if (jsonObj.get("allOf") != null && !jsonObj.get("allOf").isJsonNull()) { + WrapperAllOf.validateJsonObject(jsonObj.getAsJsonObject("allOf")); + } + // validate the optional field \`anyOf\` + if (jsonObj.get("anyOf") != null && !jsonObj.get("anyOf").isJsonNull()) { + WrapperAnyOf.validateJsonObject(jsonObj.getAsJsonObject("anyOf")); + } + // validate the optional field \`oneOf\` + if (jsonObj.get("oneOf") != null && !jsonObj.get("oneOf").isJsonNull()) { + WrapperOneOf.validateJsonObject(jsonObj.getAsJsonObject("oneOf")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Wrapper.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Wrapper' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Wrapper.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Wrapper value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Wrapper read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Wrapper given an JSON string + * + * @param jsonString JSON string + * @return An instance of Wrapper + * @throws IOException if the JSON string is invalid with respect to Wrapper + */ + public static Wrapper fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Wrapper.class); + } + + /** + * Convert an instance of Wrapper to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/WrapperAllOf.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.AllOfInlineAndRefs; +import test.test.runtime.model.AllOfRefs; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * WrapperAllOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class WrapperAllOf { + public static final String SERIALIZED_NAME_REFS = "refs"; + @SerializedName(SERIALIZED_NAME_REFS) + private AllOfRefs refs; + + public static final String SERIALIZED_NAME_INLINE_AND_REFS = "inlineAndRefs"; + @SerializedName(SERIALIZED_NAME_INLINE_AND_REFS) + private AllOfInlineAndRefs inlineAndRefs; + + public WrapperAllOf() { + } + + public WrapperAllOf refs(AllOfRefs refs) { + + this.refs = refs; + return this; + } + + /** + * Get refs + * @return refs + **/ + @javax.annotation.Nullable + + public AllOfRefs getRefs() { + return refs; + } + + + public void setRefs(AllOfRefs refs) { + this.refs = refs; + } + + + public WrapperAllOf inlineAndRefs(AllOfInlineAndRefs inlineAndRefs) { + + this.inlineAndRefs = inlineAndRefs; + return this; + } + + /** + * Get inlineAndRefs + * @return inlineAndRefs + **/ + @javax.annotation.Nullable + + public AllOfInlineAndRefs getInlineAndRefs() { + return inlineAndRefs; + } + + + public void setInlineAndRefs(AllOfInlineAndRefs inlineAndRefs) { + this.inlineAndRefs = inlineAndRefs; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WrapperAllOf wrapperAllOf = (WrapperAllOf) o; + return Objects.equals(this.refs, wrapperAllOf.refs) && + Objects.equals(this.inlineAndRefs, wrapperAllOf.inlineAndRefs); + } + + @Override + public int hashCode() { + return Objects.hash(refs, inlineAndRefs); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WrapperAllOf {\\n"); + sb.append(" refs: ").append(toIndentedString(refs)).append("\\n"); + sb.append(" inlineAndRefs: ").append(toIndentedString(inlineAndRefs)).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("refs"); + openapiFields.add("inlineAndRefs"); + + // 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 WrapperAllOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!WrapperAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in WrapperAllOf is not found in the empty JSON string", WrapperAllOf.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!WrapperAllOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`WrapperAllOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // validate the optional field \`refs\` + if (jsonObj.get("refs") != null && !jsonObj.get("refs").isJsonNull()) { + AllOfRefs.validateJsonObject(jsonObj.getAsJsonObject("refs")); + } + // validate the optional field \`inlineAndRefs\` + if (jsonObj.get("inlineAndRefs") != null && !jsonObj.get("inlineAndRefs").isJsonNull()) { + AllOfInlineAndRefs.validateJsonObject(jsonObj.getAsJsonObject("inlineAndRefs")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!WrapperAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'WrapperAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(WrapperAllOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, WrapperAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public WrapperAllOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of WrapperAllOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of WrapperAllOf + * @throws IOException if the JSON string is invalid with respect to WrapperAllOf + */ + public static WrapperAllOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, WrapperAllOf.class); + } + + /** + * Convert an instance of WrapperAllOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/WrapperAnyOf.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.AnyOfInlineAndRefs; +import test.test.runtime.model.AnyOfPrimitives; +import test.test.runtime.model.AnyOfPrimitivesAndRefs; +import test.test.runtime.model.AnyOfRefs; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * WrapperAnyOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class WrapperAnyOf { + public static final String SERIALIZED_NAME_REFS = "refs"; + @SerializedName(SERIALIZED_NAME_REFS) + private AnyOfRefs refs; + + public static final String SERIALIZED_NAME_INLINE_AND_REFS = "inlineAndRefs"; + @SerializedName(SERIALIZED_NAME_INLINE_AND_REFS) + private AnyOfInlineAndRefs inlineAndRefs; + + public static final String SERIALIZED_NAME_PRIMITIVES = "primitives"; + @SerializedName(SERIALIZED_NAME_PRIMITIVES) + private AnyOfPrimitives primitives; + + public static final String SERIALIZED_NAME_PRIMITIVES_AND_REFS = "primitivesAndRefs"; + @SerializedName(SERIALIZED_NAME_PRIMITIVES_AND_REFS) + private AnyOfPrimitivesAndRefs primitivesAndRefs; + + public WrapperAnyOf() { + } + + public WrapperAnyOf refs(AnyOfRefs refs) { + + this.refs = refs; + return this; + } + + /** + * Get refs + * @return refs + **/ + @javax.annotation.Nullable + + public AnyOfRefs getRefs() { + return refs; + } + + + public void setRefs(AnyOfRefs refs) { + this.refs = refs; + } + + + public WrapperAnyOf inlineAndRefs(AnyOfInlineAndRefs inlineAndRefs) { + + this.inlineAndRefs = inlineAndRefs; + return this; + } + + /** + * Get inlineAndRefs + * @return inlineAndRefs + **/ + @javax.annotation.Nullable + + public AnyOfInlineAndRefs getInlineAndRefs() { + return inlineAndRefs; + } + + + public void setInlineAndRefs(AnyOfInlineAndRefs inlineAndRefs) { + this.inlineAndRefs = inlineAndRefs; + } + + + public WrapperAnyOf primitives(AnyOfPrimitives primitives) { + + this.primitives = primitives; + return this; + } + + /** + * Get primitives + * @return primitives + **/ + @javax.annotation.Nullable + + public AnyOfPrimitives getPrimitives() { + return primitives; + } + + + public void setPrimitives(AnyOfPrimitives primitives) { + this.primitives = primitives; + } + + + public WrapperAnyOf primitivesAndRefs(AnyOfPrimitivesAndRefs primitivesAndRefs) { + + this.primitivesAndRefs = primitivesAndRefs; + return this; + } + + /** + * Get primitivesAndRefs + * @return primitivesAndRefs + **/ + @javax.annotation.Nullable + + public AnyOfPrimitivesAndRefs getPrimitivesAndRefs() { + return primitivesAndRefs; + } + + + public void setPrimitivesAndRefs(AnyOfPrimitivesAndRefs primitivesAndRefs) { + this.primitivesAndRefs = primitivesAndRefs; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WrapperAnyOf wrapperAnyOf = (WrapperAnyOf) o; + return Objects.equals(this.refs, wrapperAnyOf.refs) && + Objects.equals(this.inlineAndRefs, wrapperAnyOf.inlineAndRefs) && + Objects.equals(this.primitives, wrapperAnyOf.primitives) && + Objects.equals(this.primitivesAndRefs, wrapperAnyOf.primitivesAndRefs); + } + + @Override + public int hashCode() { + return Objects.hash(refs, inlineAndRefs, primitives, primitivesAndRefs); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WrapperAnyOf {\\n"); + sb.append(" refs: ").append(toIndentedString(refs)).append("\\n"); + sb.append(" inlineAndRefs: ").append(toIndentedString(inlineAndRefs)).append("\\n"); + sb.append(" primitives: ").append(toIndentedString(primitives)).append("\\n"); + sb.append(" primitivesAndRefs: ").append(toIndentedString(primitivesAndRefs)).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("refs"); + openapiFields.add("inlineAndRefs"); + openapiFields.add("primitives"); + openapiFields.add("primitivesAndRefs"); + + // 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 WrapperAnyOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!WrapperAnyOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in WrapperAnyOf is not found in the empty JSON string", WrapperAnyOf.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!WrapperAnyOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`WrapperAnyOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // validate the optional field \`refs\` + if (jsonObj.get("refs") != null && !jsonObj.get("refs").isJsonNull()) { + AnyOfRefs.validateJsonObject(jsonObj.getAsJsonObject("refs")); + } + // validate the optional field \`inlineAndRefs\` + if (jsonObj.get("inlineAndRefs") != null && !jsonObj.get("inlineAndRefs").isJsonNull()) { + AnyOfInlineAndRefs.validateJsonObject(jsonObj.getAsJsonObject("inlineAndRefs")); + } + // validate the optional field \`primitives\` + if (jsonObj.get("primitives") != null && !jsonObj.get("primitives").isJsonNull()) { + AnyOfPrimitives.validateJsonObject(jsonObj.getAsJsonObject("primitives")); + } + // validate the optional field \`primitivesAndRefs\` + if (jsonObj.get("primitivesAndRefs") != null && !jsonObj.get("primitivesAndRefs").isJsonNull()) { + AnyOfPrimitivesAndRefs.validateJsonObject(jsonObj.getAsJsonObject("primitivesAndRefs")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!WrapperAnyOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'WrapperAnyOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(WrapperAnyOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, WrapperAnyOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public WrapperAnyOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of WrapperAnyOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of WrapperAnyOf + * @throws IOException if the JSON string is invalid with respect to WrapperAnyOf + */ + public static WrapperAnyOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, WrapperAnyOf.class); + } + + /** + * Convert an instance of WrapperAnyOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/WrapperOneOf.java": "/* + * composite models + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 test.test.runtime.model.OneOfInlineAndRefs; +import test.test.runtime.model.OneOfPrimitives; +import test.test.runtime.model.OneOfPrimitivesAndRefs; +import test.test.runtime.model.OneOfRefs; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * WrapperOneOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class WrapperOneOf { + public static final String SERIALIZED_NAME_REFS = "refs"; + @SerializedName(SERIALIZED_NAME_REFS) + private OneOfRefs refs; + + public static final String SERIALIZED_NAME_INLINE_AND_REFS = "inlineAndRefs"; + @SerializedName(SERIALIZED_NAME_INLINE_AND_REFS) + private OneOfInlineAndRefs inlineAndRefs; + + public static final String SERIALIZED_NAME_PRIMITIVES = "primitives"; + @SerializedName(SERIALIZED_NAME_PRIMITIVES) + private OneOfPrimitives primitives; + + public static final String SERIALIZED_NAME_PRIMITIVES_AND_REFS = "primitivesAndRefs"; + @SerializedName(SERIALIZED_NAME_PRIMITIVES_AND_REFS) + private OneOfPrimitivesAndRefs primitivesAndRefs; + + public WrapperOneOf() { + } + + public WrapperOneOf refs(OneOfRefs refs) { + + this.refs = refs; + return this; + } + + /** + * Get refs + * @return refs + **/ + @javax.annotation.Nullable + + public OneOfRefs getRefs() { + return refs; + } + + + public void setRefs(OneOfRefs refs) { + this.refs = refs; + } + + + public WrapperOneOf inlineAndRefs(OneOfInlineAndRefs inlineAndRefs) { + + this.inlineAndRefs = inlineAndRefs; + return this; + } + + /** + * Get inlineAndRefs + * @return inlineAndRefs + **/ + @javax.annotation.Nullable + + public OneOfInlineAndRefs getInlineAndRefs() { + return inlineAndRefs; + } + + + public void setInlineAndRefs(OneOfInlineAndRefs inlineAndRefs) { + this.inlineAndRefs = inlineAndRefs; + } + + + public WrapperOneOf primitives(OneOfPrimitives primitives) { + + this.primitives = primitives; + return this; + } + + /** + * Get primitives + * @return primitives + **/ + @javax.annotation.Nullable + + public OneOfPrimitives getPrimitives() { + return primitives; + } + + + public void setPrimitives(OneOfPrimitives primitives) { + this.primitives = primitives; + } + + + public WrapperOneOf primitivesAndRefs(OneOfPrimitivesAndRefs primitivesAndRefs) { + + this.primitivesAndRefs = primitivesAndRefs; + return this; + } + + /** + * Get primitivesAndRefs + * @return primitivesAndRefs + **/ + @javax.annotation.Nullable + + public OneOfPrimitivesAndRefs getPrimitivesAndRefs() { + return primitivesAndRefs; + } + + + public void setPrimitivesAndRefs(OneOfPrimitivesAndRefs primitivesAndRefs) { + this.primitivesAndRefs = primitivesAndRefs; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WrapperOneOf wrapperOneOf = (WrapperOneOf) o; + return Objects.equals(this.refs, wrapperOneOf.refs) && + Objects.equals(this.inlineAndRefs, wrapperOneOf.inlineAndRefs) && + Objects.equals(this.primitives, wrapperOneOf.primitives) && + Objects.equals(this.primitivesAndRefs, wrapperOneOf.primitivesAndRefs); + } + + @Override + public int hashCode() { + return Objects.hash(refs, inlineAndRefs, primitives, primitivesAndRefs); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WrapperOneOf {\\n"); + sb.append(" refs: ").append(toIndentedString(refs)).append("\\n"); + sb.append(" inlineAndRefs: ").append(toIndentedString(inlineAndRefs)).append("\\n"); + sb.append(" primitives: ").append(toIndentedString(primitives)).append("\\n"); + sb.append(" primitivesAndRefs: ").append(toIndentedString(primitivesAndRefs)).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("refs"); + openapiFields.add("inlineAndRefs"); + openapiFields.add("primitives"); + openapiFields.add("primitivesAndRefs"); + + // 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 WrapperOneOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!WrapperOneOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in WrapperOneOf is not found in the empty JSON string", WrapperOneOf.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!WrapperOneOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`WrapperOneOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // validate the optional field \`refs\` + if (jsonObj.get("refs") != null && !jsonObj.get("refs").isJsonNull()) { + OneOfRefs.validateJsonObject(jsonObj.getAsJsonObject("refs")); + } + // validate the optional field \`inlineAndRefs\` + if (jsonObj.get("inlineAndRefs") != null && !jsonObj.get("inlineAndRefs").isJsonNull()) { + OneOfInlineAndRefs.validateJsonObject(jsonObj.getAsJsonObject("inlineAndRefs")); + } + // validate the optional field \`primitives\` + if (jsonObj.get("primitives") != null && !jsonObj.get("primitives").isJsonNull()) { + OneOfPrimitives.validateJsonObject(jsonObj.getAsJsonObject("primitives")); + } + // validate the optional field \`primitivesAndRefs\` + if (jsonObj.get("primitivesAndRefs") != null && !jsonObj.get("primitivesAndRefs").isJsonNull()) { + OneOfPrimitivesAndRefs.validateJsonObject(jsonObj.getAsJsonObject("primitivesAndRefs")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!WrapperOneOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'WrapperOneOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(WrapperOneOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, WrapperOneOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public WrapperOneOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of WrapperOneOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of WrapperOneOf + * @throws IOException if the JSON string is invalid with respect to WrapperOneOf + */ + public static WrapperOneOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, WrapperOneOf.class); + } + + /** + * Convert an instance of WrapperOneOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", +} +`; + +exports[`Java Client Code Generation Script Unit Tests Generates With data-types.yaml 1`] = ` +{ + ".github/workflows/maven.yml": "# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build Data Types + runs-on: ubuntu-latest + strategy: + matrix: + java: [ '8' ] + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: \${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml +", + ".gitignore": "*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build +", + ".openapi-generator-ignore": "# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md +", + ".openapi-generator/FILES": ".github/workflows/maven.yml +.gitignore +.openapi-generator-ignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/DataTypes200Response.md +docs/DataTypes200ResponseMyAllOf.md +docs/DataTypes200ResponseMyAllOfAllOf.md +docs/DataTypes200ResponseMyAllOfAllOf1.md +docs/DataTypes200ResponseMyAnyOf.md +docs/DataTypes200ResponseMyNotNot.md +docs/DataTypes200ResponseMyObject.md +docs/DataTypes200ResponseMyObjectOne.md +docs/DataTypes200ResponseMyObjectOneTwo.md +docs/DataTypes200ResponseMyOneOf.md +docs/DefaultApi.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/test/test/runtime/ApiCallback.java +src/main/java/test/test/runtime/ApiClient.java +src/main/java/test/test/runtime/ApiException.java +src/main/java/test/test/runtime/ApiResponse.java +src/main/java/test/test/runtime/Configuration.java +src/main/java/test/test/runtime/GzipRequestInterceptor.java +src/main/java/test/test/runtime/JSON.java +src/main/java/test/test/runtime/Pair.java +src/main/java/test/test/runtime/ProgressRequestBody.java +src/main/java/test/test/runtime/ProgressResponseBody.java +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/__handlers.java +src/main/java/test/test/runtime/__interceptors.java +src/main/java/test/test/runtime/api/DefaultApi.java +src/main/java/test/test/runtime/api/operation_config/OperationConfig.java +src/main/java/test/test/runtime/api/operation_config/OperationLookup.java +src/main/java/test/test/runtime/api/operation_config/Operations.java +src/main/java/test/test/runtime/auth/ApiKeyAuth.java +src/main/java/test/test/runtime/auth/Authentication.java +src/main/java/test/test/runtime/auth/HttpBasicAuth.java +src/main/java/test/test/runtime/auth/HttpBearerAuth.java +src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java +src/main/java/test/test/runtime/model/DataTypes200Response.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOf.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf1.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyAnyOf.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyNotNot.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyObject.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyObjectOne.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyObjectOneTwo.java +src/main/java/test/test/runtime/model/DataTypes200ResponseMyOneOf.java +src/test/java/test/test/runtime/api/DefaultApiTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf1Test.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOfTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyAllOfTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyAnyOfTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyNotNotTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyObjectOneTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyObjectOneTwoTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyObjectTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseMyOneOfTest.java +src/test/java/test/test/runtime/model/DataTypes200ResponseTest.java +src/main/java/test/test/runtime/api/handlers/Handlers.java +src/main/java/test/test/runtime/api/handlers/Response.java +src/main/java/test/test/runtime/api/handlers/ApiResponse.java +src/main/java/test/test/runtime/api/handlers/Interceptor.java +src/main/java/test/test/runtime/api/handlers/Interceptors.java +src/main/java/test/test/runtime/api/handlers/HandlerChain.java +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/data_types/DataTypesResponse.java +src/main/java/test/test/runtime/api/handlers/data_types/DataTypes200Response.java +src/main/java/test/test/runtime/api/handlers/data_types/DataTypesRequestParameters.java +src/main/java/test/test/runtime/api/handlers/data_types/DataTypesInput.java +src/main/java/test/test/runtime/api/handlers/data_types/DataTypesRequestInput.java +src/main/java/test/test/runtime/api/handlers/data_types/DataTypes.java +src/main/java/test/test/runtime/api/handlers/HandlerRouter.java +src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java +src/main/java/test/test/runtime/api/interceptors/ResponseHeadersInterceptor.java +src/main/java/test/test/runtime/api/interceptors/powertools/LoggingInterceptor.java +src/main/java/test/test/runtime/api/interceptors/powertools/TracingInterceptor.java +src/main/java/test/test/runtime/api/interceptors/powertools/MetricsInterceptor.java +src/main/java/test/test/runtime/api/interceptors/DefaultInterceptors.java", + ".openapi-generator/VERSION": "6.3.0", + ".pdk/dynamic-files/openapitools.json": "{ + "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "spaces": 2, + "generator-cli": { + "version": "6.3.0", + "storageDir": "~/.open-api-generator-cli" + }, + "//": "~~ Generated by projen. To modify, edit src/test/java/projenrc.java and run \\"npx projen\\"." +} +", + "README.md": "# com.aws.pdk.test + +Data Types +- API version: 1.0.0 + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: +1. Java 1.8+ +2. Maven (3.8.3+)/Gradle (7.2+) + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +\`\`\`shell +mvn clean install +\`\`\` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +\`\`\`shell +mvn clean deploy +\`\`\` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +\`\`\`xml + + test + com.aws.pdk.test + 1.0.0 + compile + +\`\`\` + +### Gradle users + +Add this dependency to your project's build file: + +\`\`\`groovy + repositories { + mavenCentral() // Needed if the 'com.aws.pdk.test' jar has been published to maven central. + mavenLocal() // Needed if the 'com.aws.pdk.test' jar has been published to the local maven repo. + } + + dependencies { + implementation "test:com.aws.pdk.test:1.0.0" + } +\`\`\` + +### Others + +At first generate the JAR by executing: + +\`\`\`shell +mvn clean package +\`\`\` + +Then manually install the following JARs: + +* \`target/com.aws.pdk.test-1.0.0.jar\` +* \`target/lib/*.jar\` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +\`\`\`java + +// Import classes: +import test.test.runtime.ApiClient; +import test.test.runtime.ApiException; +import test.test.runtime.Configuration; +import test.test.runtime.models.*; +import test.test.runtime.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + DataTypes200Response result = apiInstance.dataTypes() + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#dataTypes"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +\`\`\` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**dataTypes**](docs/DefaultApi.md#dataTypes) | **GET** /types | + + +## Documentation for Models + + - [DataTypes200Response](docs/DataTypes200Response.md) + - [DataTypes200ResponseMyAllOf](docs/DataTypes200ResponseMyAllOf.md) + - [DataTypes200ResponseMyAllOfAllOf](docs/DataTypes200ResponseMyAllOfAllOf.md) + - [DataTypes200ResponseMyAllOfAllOf1](docs/DataTypes200ResponseMyAllOfAllOf1.md) + - [DataTypes200ResponseMyAnyOf](docs/DataTypes200ResponseMyAnyOf.md) + - [DataTypes200ResponseMyNotNot](docs/DataTypes200ResponseMyNotNot.md) + - [DataTypes200ResponseMyObject](docs/DataTypes200ResponseMyObject.md) + - [DataTypes200ResponseMyObjectOne](docs/DataTypes200ResponseMyObjectOne.md) + - [DataTypes200ResponseMyObjectOneTwo](docs/DataTypes200ResponseMyObjectOneTwo.md) + - [DataTypes200ResponseMyOneOf](docs/DataTypes200ResponseMyOneOf.md) + + +## Documentation for Authorization + +All endpoints do not require authorization. +Authentication schemes defined for the API: + +## Recommendation + +It's recommended to create an instance of \`ApiClient\` per thread in a multithreaded environment to avoid any potential issues. + +## Author + + + +", + "api/openapi.yaml": "openapi: 3.0.3 +info: + title: Data Types + version: 1.0.0 +servers: +- url: / +paths: + /types: + get: + operationId: dataTypes + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/dataTypes_200_response' + description: Ok + x-accepts: application/json +components: + schemas: + dataTypes_200_response_myObject_one: + properties: + twoString: + type: string + two: + $ref: '#/components/schemas/dataTypes_200_response_myObject_one_two' + type: object + dataTypes_200_response_myAllOf_allOf_1: + properties: + second: + type: string + type: object + dataTypes_200_response_myOneOf: + oneOf: + - type: string + - type: number + dataTypes_200_response_myAllOf: + allOf: + - $ref: '#/components/schemas/dataTypes_200_response_myAllOf_allOf' + - $ref: '#/components/schemas/dataTypes_200_response_myAllOf_allOf_1' + dataTypes_200_response_myObject: + properties: + one: + $ref: '#/components/schemas/dataTypes_200_response_myObject_one' + oneString: + type: string + type: object + dataTypes_200_response_myAllOf_allOf: + properties: + first: + type: string + type: object + dataTypes_200_response: + properties: + myInt: + maximum: 7 + minimum: 3 + type: integer + myString: + type: string + myStringLength: + maxLength: 5 + minLength: 4 + type: string + myLongMinStringLength: + minLength: 1000 + type: string + myBool: + type: boolean + myNumber: + type: number + myDateArray: + items: + format: date + type: string + type: array + myEmail: + format: email + type: string + myUrl: + format: uri + type: string + myHostname: + format: hostname + type: string + myIpv4: + format: ipv4 + type: string + myIpv6: + format: ipv6 + type: string + myUuid: + format: uuid + type: string + myByte: + format: byte + type: string + myDateTime: + format: date-time + type: string + myRegexPattern: + pattern: "^\\\\d{4}-pattern-[a-z]+$" + type: string + myOneOf: + $ref: '#/components/schemas/dataTypes_200_response_myOneOf' + myAnyOf: + $ref: '#/components/schemas/dataTypes_200_response_myAnyOf' + myAllOf: + $ref: '#/components/schemas/dataTypes_200_response_myAllOf' + myNot: + not: + $ref: '#/components/schemas/dataTypes_200_response_myNot_not' + myNotString: + not: + type: string + myAdditionalProperties: + additionalProperties: + items: + maximum: 20 + minimum: 10 + type: integer + maxItems: 5 + minItems: 2 + type: array + type: object + myObject: + $ref: '#/components/schemas/dataTypes_200_response_myObject' + type: object + dataTypes_200_response_myAnyOf: + anyOf: + - type: string + - type: number + dataTypes_200_response_myNot_not: + properties: + foo: + type: string + type: object + dataTypes_200_response_myObject_one_two: + properties: + threeString: + type: string + type: object + +", + "docs/DataTypes200Response.md": " + +# DataTypes200Response + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**myInt** | **Integer** | | [optional] | +|**myString** | **String** | | [optional] | +|**myStringLength** | **String** | | [optional] | +|**myLongMinStringLength** | **String** | | [optional] | +|**myBool** | **Boolean** | | [optional] | +|**myNumber** | **BigDecimal** | | [optional] | +|**myDateArray** | **List<LocalDate>** | | [optional] | +|**myEmail** | **String** | | [optional] | +|**myUrl** | **URI** | | [optional] | +|**myHostname** | **String** | | [optional] | +|**myIpv4** | **String** | | [optional] | +|**myIpv6** | **String** | | [optional] | +|**myUuid** | **UUID** | | [optional] | +|**myByte** | **byte[]** | | [optional] | +|**myDateTime** | **OffsetDateTime** | | [optional] | +|**myRegexPattern** | **String** | | [optional] | +|**myOneOf** | [**DataTypes200ResponseMyOneOf**](DataTypes200ResponseMyOneOf.md) | | [optional] | +|**myAnyOf** | [**DataTypes200ResponseMyAnyOf**](DataTypes200ResponseMyAnyOf.md) | | [optional] | +|**myAllOf** | [**DataTypes200ResponseMyAllOf**](DataTypes200ResponseMyAllOf.md) | | [optional] | +|**myNot** | **Object** | | [optional] | +|**myNotString** | **Object** | | [optional] | +|**myAdditionalProperties** | **Map<String, List<Integer>>** | | [optional] | +|**myObject** | [**DataTypes200ResponseMyObject**](DataTypes200ResponseMyObject.md) | | [optional] | + + + +", + "docs/DataTypes200ResponseMyAllOf.md": " + +# DataTypes200ResponseMyAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**first** | **String** | | [optional] | +|**second** | **String** | | [optional] | + + + +", + "docs/DataTypes200ResponseMyAllOfAllOf.md": " + +# DataTypes200ResponseMyAllOfAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**first** | **String** | | [optional] | + + + +", + "docs/DataTypes200ResponseMyAllOfAllOf1.md": " + +# DataTypes200ResponseMyAllOfAllOf1 + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**second** | **String** | | [optional] | + + + +", + "docs/DataTypes200ResponseMyAnyOf.md": " + +# DataTypes200ResponseMyAnyOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + +", + "docs/DataTypes200ResponseMyNotNot.md": " + +# DataTypes200ResponseMyNotNot + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**foo** | **String** | | [optional] | + + + +", + "docs/DataTypes200ResponseMyObject.md": " + +# DataTypes200ResponseMyObject + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**one** | [**DataTypes200ResponseMyObjectOne**](DataTypes200ResponseMyObjectOne.md) | | [optional] | +|**oneString** | **String** | | [optional] | + + + +", + "docs/DataTypes200ResponseMyObjectOne.md": " + +# DataTypes200ResponseMyObjectOne + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**twoString** | **String** | | [optional] | +|**two** | [**DataTypes200ResponseMyObjectOneTwo**](DataTypes200ResponseMyObjectOneTwo.md) | | [optional] | + + + +", + "docs/DataTypes200ResponseMyObjectOneTwo.md": " + +# DataTypes200ResponseMyObjectOneTwo + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**threeString** | **String** | | [optional] | + + + +", + "docs/DataTypes200ResponseMyOneOf.md": " + +# DataTypes200ResponseMyOneOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + +", + "docs/DefaultApi.md": "# DefaultApi + +All URIs are relative to *http://localhost* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**dataTypes**](DefaultApi.md#dataTypes) | **GET** /types | | + + + +# **dataTypes** +> DataTypes200Response dataTypes().execute(); + + + +### Example +\`\`\`java +// Import classes: +import test.test.runtime.ApiClient; +import test.test.runtime.ApiException; +import test.test.runtime.Configuration; +import test.test.runtime.models.*; +import test.test.runtime.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + DataTypes200Response result = apiInstance.dataTypes() + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#dataTypes"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +\`\`\` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**DataTypes200Response**](DataTypes200Response.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Ok | - | + +", + "openapitools.json": "{ + "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "spaces": 2, + "generator-cli": { + "version": "6.3.0", + "storageDir": "~/.open-api-generator-cli" + }, + "//": "~~ Generated by projen. To modify, edit src/test/java/projenrc.java and run \\"npx projen\\"." +} +", + "src/main/java/test/test/runtime/ApiCallback.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} +", + "src/main/java/test/test/runtime/ApiClient.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import okhttp3.*; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.tls.OkHostnameVerifier; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; + +import javax.net.ssl.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URI; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.DateFormat; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import test.test.runtime.auth.Authentication; +import test.test.runtime.auth.HttpBasicAuth; +import test.test.runtime.auth.HttpBearerAuth; +import test.test.runtime.auth.ApiKeyAuth; + +/** + *

ApiClient class.

+ */ +public class ApiClient { + + private String basePath = "http://localhost"; + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "", + "No description provided", + new HashMap() + ) + )); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private Map defaultCookieMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + private KeyManager[] keyManagers; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /** + * Basic constructor for ApiClient + */ + public ApiClient() { + init(); + initHttpClient(); + + // Setup authentications (key: authentication name, value: authentication). + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Basic constructor with custom OkHttpClient + * + * @param client a {@link okhttp3.OkHttpClient} object + */ + public ApiClient(OkHttpClient client) { + init(); + + httpClient = client; + + // Setup authentications (key: authentication name, value: authentication). + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + private void initHttpClient() { + initHttpClient(Collections.emptyList()); + } + + private void initHttpClient(List interceptors) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.addNetworkInterceptor(getProgressInterceptor()); + for (Interceptor interceptor: interceptors) { + builder.addInterceptor(interceptor); + } + + httpClient = builder.build(); + } + + private void init() { + verifyingSsl = true; + + json = new JSON(); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/1.0.0/java"); + + authentications = new HashMap(); + } + + /** + * Get base path + * + * @return Base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://localhost + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client, which must never be null. + * + * @param newHttpClient An instance of OkHttpClient + * @return Api Client + * @throws java.lang.NullPointerException when newHttpClient is null + */ + public ApiClient setHttpClient(OkHttpClient newHttpClient) { + this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + /** + *

Getter for the field keyManagers.

+ * + * @return an array of {@link javax.net.ssl.KeyManager} objects + */ + public KeyManager[] getKeyManagers() { + return keyManagers; + } + + /** + * Configure client keys to use for authorization in an SSL session. + * Use null to reset to default. + * + * @param managers The KeyManagers to use + * @return ApiClient + */ + public ApiClient setKeyManagers(KeyManager[] managers) { + this.keyManagers = managers; + applySslSettings(); + return this; + } + + /** + *

Getter for the field dateFormat.

+ * + * @return a {@link java.text.DateFormat} object + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + *

Setter for the field dateFormat.

+ * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link test.test.runtime.ApiClient} object + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + JSON.setDateFormat(dateFormat); + return this; + } + + /** + *

Set SqlDateFormat.

+ * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link test.test.runtime.ApiClient} object + */ + public ApiClient setSqlDateFormat(DateFormat dateFormat) { + JSON.setSqlDateFormat(dateFormat); + return this; + } + + /** + *

Set OffsetDateTimeFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link test.test.runtime.ApiClient} object + */ + public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.setOffsetDateTimeFormat(dateFormat); + return this; + } + + /** + *

Set LocalDateFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link test.test.runtime.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + /** + *

Set LenientOnJson.

+ * + * @param lenientOnJson a boolean + * @return a {@link test.test.runtime.ApiClient} object + */ + public ApiClient setLenientOnJson(boolean lenientOnJson) { + JSON.setLenientOnJson(lenientOnJson); + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Helper method to set credentials for AWSV4 Signature + * + * @param accessKey Access Key + * @param secretKey Secret Key + * @param region Region + * @param service Service to access to + */ + public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { + throw new RuntimeException("No AWS4 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return ApiClient + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); + } else { + final OkHttpClient.Builder builder = httpClient.newBuilder(); + builder.interceptors().remove(loggingInterceptor); + httpClient = builder.build(); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default temporary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the temporary folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.connectTimeoutMillis(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.readTimeoutMillis(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.writeTimeoutMillis(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { + //Serialize to json string and remove the " enclosing characters + String jsonStr = JSON.serialize(param); + return jsonStr.substring(1, jsonStr.length() - 1); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection) param) { + if (b.length() > 0) { + b.append(","); + } + b.append(o); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified query parameter to a list containing a single {@code Pair} object. + * + * Note that {@code value} must not be a collection. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list containing a single {@code Pair} object. + */ + public List parameterToPair(String name, Object value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value instanceof Collection) { + return params; + } + + params.add(new Pair(name, parameterToString(value))); + return params; + } + + /** + * Formats the specified collection query parameters to a list of {@code Pair} objects. + * + * Note that the values of each of the returned Pair objects are percent-encoded. + * + * @param collectionFormat The collection format of the parameter. + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list of {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Collection value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { + return params; + } + + // create the params based on the collection format + if ("multi".equals(collectionFormat)) { + for (Object item : value) { + params.add(new Pair(name, escapeString(parameterToString(item)))); + } + return params; + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + // escape all delimiters except commas, which are URI reserved + // characters + if ("ssv".equals(collectionFormat)) { + delimiter = escapeString(" "); + } else if ("tsv".equals(collectionFormat)) { + delimiter = escapeString("\\t"); + } else if ("pipes".equals(collectionFormat)) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(name, sb.substring(delimiter.length()))); + + return params; + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param value The value of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(String collectionFormat, Collection value) { + // create the value based on the collection format + if ("multi".equals(collectionFormat)) { + // not valid for path params + return parameterToString(value); + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + if ("ssv".equals(collectionFormat)) { + delimiter = " "; + } else if ("tsv".equals(collectionFormat)) { + delimiter = "\\t"; + } else if ("pipes".equals(collectionFormat)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \\t]+/[^;/ \\t]+[+]json)[ \\t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * returns null. If it matches "any", JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + + if (contentTypes[0].equals("*/*")) { + return "application/json"; + } + + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws test.test.runtime.ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return JSON.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \\"" + contentType + "\\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws test.test.runtime.ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else { + throw new ApiException("Content type \\"" + contentType + "\\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws test.test.runtime.ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @return Prepared file for the download + * @throws java.io.IOException If fail to prepare file for download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\\"]?([^'\\"\\\\s]+)['\\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return Files.createTempFile(prefix, suffix).toFile(); + else + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @return ApiResponse<T> + * @throws test.test.runtime.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws test.test.runtime.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + * @see #execute(Call, Type) + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @return Type + * @throws test.test.runtime.ApiException If the response has an unsuccessful status code or + * fail to deserialize the response body + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + if (response.body() != null) { + try { + response.body().close(); + } catch (Exception e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP call + * @throws test.test.runtime.ApiException If fail to serialize the request body object + */ + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + + return httpClient.newCall(request); + } + + /** + * Build an HTTP request with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP request + * @throws test.test.runtime.ApiException If fail to serialize the request body object + */ + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams + List allQueryParams = new ArrayList(queryParams); + allQueryParams.addAll(collectionQueryParams); + + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); + + // prepare HTTP request body + RequestBody reqBody; + String contentType = headerParams.get("Content-Type"); + + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); + } + } else { + reqBody = serialize(body, contentType); + } + + // update parameters with authentication settings + updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); + + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + processCookieParams(cookieParams, reqBuilder); + + // Associate callback with request (if not null) so interceptor can + // access it when creating ProgressResponseBody + reqBuilder.tag(callback); + + Request request = null; + + if (callback != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return request; + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param baseUrl The base URL + * @param path The sub path + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @return The full URL + */ + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { + final StringBuilder url = new StringBuilder(); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + String baseURL; + if (serverIndex != null) { + if (serverIndex < 0 || serverIndex >= servers.size()) { + throw new ArrayIndexOutOfBoundsException(String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() + )); + } + baseURL = servers.get(serverIndex).URL(serverVariables); + } else { + baseURL = basePath; + } + url.append(baseURL).append(path); + } + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in \`path\`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { + String prefix = url.toString().contains("?") ? "&" : "?"; + for (Pair param : collectionQueryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + // collection query parameter value already escaped as part of parameterToPairs + url.append(escapeString(param.getName())).append("=").append(value); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Set cookie parameters to the request builder, including default cookies. + * + * @param cookieParams Cookie parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { + for (Entry param : cookieParams.entrySet()) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @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 test.test.runtime.ApiException If fails to update the parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, + Map cookieParams, String payload, String method, URI uri) throws ApiException { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RuntimeException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); + } else if (param.getValue() instanceof List) { + List list = (List) param.getValue(); + for (Object item: list) { + if (item instanceof File) { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param file The file to add to the Header + */ + private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\\"" + key + "\\"; filename=\\"" + file.getName() + "\\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); + } + + /** + * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param obj The complex object to add to the Header + */ + private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { + RequestBody requestBody; + if (obj instanceof String) { + requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); + } else { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + requestBody = RequestBody.create(content, MediaType.parse("application/json")); + } + + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\\"" + key + "\\""); + mpBuilder.addPart(partHeaders, requestBody); + } + + /** + * Get network interceptor to add it to the httpClient to track download progress for + * async requests. + */ + private Interceptor getProgressInterceptor() { + return new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + final Request request = chain.request(); + final Response originalResponse = chain.proceed(request); + if (request.tag() instanceof ApiCallback) { + final ApiCallback callback = (ApiCallback) request.tag(); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), callback)) + .build(); + } + return originalResponse; + } + }; + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + TrustManager[] trustManagers; + HostnameVerifier hostnameVerifier; + if (!verifyingSsl) { + trustManagers = new TrustManager[]{ + new X509TrustManager() { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + } + }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } else { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + if (sslCaCert == null) { + trustManagerFactory.init((KeyStore) null); + } else { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + (index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + trustManagerFactory.init(caKeyStore); + } + trustManagers = trustManagerFactory.getTrustManagers(); + hostnameVerifier = OkHostnameVerifier.INSTANCE; + } + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient = httpClient.newBuilder() + .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) + .hostnameVerifier(hostnameVerifier) + .build(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** + * Convert the HTTP request body to a string. + * + * @param requestBody The HTTP request object + * @return The string representation of the HTTP request body + * @throws test.test.runtime.ApiException If fail to serialize the request body object into a string + */ + private String requestBodyToString(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readUtf8(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return ""; + } +} +", + "src/main/java/test/test/runtime/ApiException.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import java.util.Map; +import java.util.List; + +import javax.ws.rs.core.GenericType; + +/** + *

ApiException class.

+ */ +@SuppressWarnings("serial") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + /** + *

Constructor for ApiException.

+ */ + public ApiException() {} + + /** + *

Constructor for ApiException.

+ * + * @param throwable a {@link java.lang.Throwable} object + */ + public ApiException(Throwable throwable) { + super(throwable); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + */ + public ApiException(String message) { + super(message); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, Map> responseHeaders, String responseBody) { + this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message a {@link java.lang.String} object + */ + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message the error message + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } + + /** + * Get the exception message including HTTP response data. + * + * @return The exception message + */ + public String getMessage() { + return String.format("Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", + super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders()); + } +} +", + "src/main/java/test/test/runtime/ApiResponse.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + /** + *

Get the status code.

+ * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

Get the headers.

+ * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

Get the data.

+ * + * @return the data + */ + public T getData() { + return data; + } +} +", + "src/main/java/test/test/runtime/Configuration.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} +", + "src/main/java/test/test/runtime/GzipRequestInterceptor.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { + return chain.proceed(originalRequest); + } + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) + .build(); + return chain.proceed(compressedRequest); + } + + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + sink.write(buffer.snapshot()); + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} +", + "src/main/java/test/test/runtime/JSON.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +import io.gsonfire.TypeSelector; + +import okio.ByteString; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.HashMap; + +/* + * A JSON utility class + * + * NOTE: in the future, this class may be converted to static, which may break + * backward-compatibility + */ +public class JSON { + private static Gson gson; + private static boolean isLenientOnJson = false; + private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + + @SuppressWarnings("unchecked") + public static GsonBuilder createGson() { + GsonFireBuilder fireBuilder = new GsonFireBuilder() + ; + GsonBuilder builder = fireBuilder.createGsonBuilder(); + return builder; + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + /** + * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. + * + * @param classByDiscriminatorValue The map of discriminator values to Java classes. + * @param discriminatorValue The value of the OpenAPI discriminator in the input data. + * @return The Java class that implements the OpenAPI schema + */ + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + + { + GsonBuilder gsonBuilder = createGson(); + gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); + gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); + gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); + gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); + gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200Response.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAllOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAllOfAllOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAllOfAllOf1.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyAnyOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyNotNot.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyObject.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyObjectOne.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyObjectOneTwo.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.DataTypes200ResponseMyOneOf.CustomTypeAdapterFactory()); + gson = gsonBuilder.create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public static Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public static void setGson(Gson gson) { + JSON.gson = gson; + } + + public static void setLenientOnJson(boolean lenientOnJson) { + isLenientOnJson = lenientOnJson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public static String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public static T deserialize(String body, Type returnType) { + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + } + + /** + * Gson TypeAdapter for Byte Array type + */ + public static class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public static class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public static class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public static class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public static class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } + + public static void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } +} +", + "src/main/java/test/test/runtime/Pair.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) { + return; + } + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) { + return; + } + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) { + return false; + } + + return true; + } +} +", + "src/main/java/test/test/runtime/ProgressRequestBody.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink bufferedSink = Okio.buffer(sink(sink)); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} +", + "src/main/java/test/test/runtime/ProgressResponseBody.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} +", + "src/main/java/test/test/runtime/ServerConfiguration.java": "package test.test.runtime; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} +", + "src/main/java/test/test/runtime/ServerVariable.java": "package test.test.runtime; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} +", + "src/main/java/test/test/runtime/StringUtil.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} +", + "src/main/java/test/test/runtime/api/DefaultApi.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime.api; + +import test.test.runtime.ApiCallback; +import test.test.runtime.ApiClient; +import test.test.runtime.ApiException; +import test.test.runtime.ApiResponse; +import test.test.runtime.Configuration; +import test.test.runtime.Pair; +import test.test.runtime.ProgressRequestBody; +import test.test.runtime.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import test.test.runtime.model.DataTypes200Response; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.GenericType; + +public class DefaultApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public DefaultApi() { + this(Configuration.getDefaultApiClient()); + } + + public DefaultApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + private okhttp3.Call dataTypesCall(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 = "/types"; + + 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, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call dataTypesValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return dataTypesCall(_callback); + + } + + + private ApiResponse dataTypesWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = dataTypesValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + private okhttp3.Call dataTypesAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = dataTypesValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIdataTypesRequest { + + private APIdataTypesRequest() { + } + + /** + * Build call for dataTypes + * @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 dataTypesCall(_callback); + } + + /** + * Execute dataTypes request + * @return DataTypes200Response + * @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 DataTypes200Response execute() throws ApiException { + ApiResponse localVarResp = dataTypesWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Execute dataTypes request with HTTP info returned + * @return ApiResponse<DataTypes200Response> + * @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 dataTypesWithHttpInfo(); + } + + /** + * Execute dataTypes 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 dataTypesAsync(_callback); + } + } + + /** + * + * + * @return APIdataTypesRequest + * @http.response.details + + + +
Status Code Description Response Headers
200 Ok -
+ */ + public APIdataTypesRequest dataTypes() { + return new APIdataTypesRequest(); + } +} +", + "src/main/java/test/test/runtime/api/handlers/ApiResponse.java": " +package test.test.runtime.api.handlers; + +import java.util.Map; +import java.util.List; + +@lombok.experimental.SuperBuilder +@lombok.AllArgsConstructor +@lombok.Getter +public class ApiResponse implements Response { + private String body; + private int statusCode; + private Map headers; + private Map> multiValueHeaders; +} +", + "src/main/java/test/test/runtime/api/handlers/ChainedRequestInput.java": " +package test.test.runtime.api.handlers; + +/** + * Reqeust input with a handler chain + */ +public interface ChainedRequestInput extends RequestInput { + /** + * The chain for handling requests + */ + HandlerChain getChain(); +} +", + "src/main/java/test/test/runtime/api/handlers/HandlerChain.java": " +package test.test.runtime.api.handlers; +/** + * A handler chain represents a series of interceptors, which may or may not delegate to following interceptors. + * The lambda handler is always the last method in the chain. + */ +public interface HandlerChain { + /** + * Delegate to the remainder of the handler chain + */ + Response next(ChainedRequestInput input); +} +", + "src/main/java/test/test/runtime/api/handlers/HandlerRouter.java": " +package test.test.runtime.api.handlers; + +import test.test.runtime.api.handlers.data_types.*; + +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; + +import java.util.Map; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; + + +public abstract class HandlerRouter implements RequestHandler { + private static final String dataTypesMethodAndPath = Handlers.concatMethodAndPath("GET", "/types"); + + private final DataTypes constructedDataTypes; + + /** + * This method must return your implementation of the DataTypes operation + */ + public abstract DataTypes dataTypes(); + + private static enum Route { + dataTypesRoute, + } + + /** + * Map of method and path to the route to map to + */ + private final Map routes = new HashMap<>(); + + public HandlerRouter() { + this.routes.put(dataTypesMethodAndPath, Route.dataTypesRoute); + // 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.constructedDataTypes = this.dataTypes(); + } + + /** + * 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(); + } + + @Override + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) { + String method = event.getRequestContext().getHttpMethod(); + String path = event.getRequestContext().getResourcePath(); + String methodAndPath = Handlers.concatMethodAndPath(method, path); + Route route = this.routes.get(methodAndPath); + + switch (route) { + case dataTypesRoute: + List> dataTypesInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + dataTypesInterceptors.addAll(this.getInterceptors()); + return this.constructedDataTypes.handleRequestWithAdditionalInterceptors(event, context, dataTypesInterceptors); + default: + throw new RuntimeException(String.format("No registered handler for method {} and path {}", method, path)); + } + } +}", + "src/main/java/test/test/runtime/api/handlers/Handlers.java": " +package test.test.runtime.api.handlers; + +import test.test.runtime.model.*; +import test.test.runtime.api.interceptors.ResponseHeadersInterceptor; + +import java.util.Arrays; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; +import java.util.stream.Collectors; +import java.io.UnsupportedEncodingException; +import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.time.DateTimeException; +import java.math.BigDecimal; +import java.math.BigInteger; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; + +import test.test.runtime.model.DataTypes200Response; + +import test.test.runtime.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Handlers { + + 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 static String decodeParameter(final String parameter) { + try { + return URLDecoder.decode(parameter, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + public static Map decodeRequestParameters(Map parameters) { + Map decodedParameters = new HashMap<>(); + for(Map.Entry parameter : parameters.entrySet()) { + decodedParameters.put(parameter.getKey(), decodeParameter(parameter.getValue())); + } + return decodedParameters; + } + + public static Map> decodeRequestArrayParameters(Map> parameters) { + Map> decodedParameters = new HashMap<>(); + for(Map.Entry> parameter : parameters.entrySet()) { + decodedParameters.put(parameter.getKey(), parameter.getValue().stream().map(Handlers::decodeParameter).collect(Collectors.toList())); + } + return decodedParameters; + } + + public static void assertRequired(final Boolean required, final String baseName, final Map parameters) { + if (required && parameters.get(baseName) == null) { + throw new RuntimeException("Missing required request parameter '" + baseName + "'"); + } + } + + public static String coerceStringParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + return parameters.get(baseName); + } + + public static List coerceStringArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + return parameters.get(baseName); + } + + public static Double coerceDouble(final String baseName, final String s) { + try { + return Double.valueOf(s); + } catch (NumberFormatException e) { + throw new RuntimeException("Expected a number for request parameter '" + baseName + "'"); + } + } + + public static Double coerceDoubleParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceDouble(baseName, s); + } + + public static List coerceDoubleArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceDouble(baseName, s)); + } + return res; + } + + public static BigDecimal coerceBigDecimal(final String baseName, final String s) { + try { + return new BigDecimal(s); + } catch (NumberFormatException e) { + throw new RuntimeException("Expected a number for request parameter '" + baseName + "'"); + } + } + + public static BigDecimal coerceBigDecimalParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceBigDecimal(baseName, s); + } + + public static List coerceBigDecimalArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceBigDecimal(baseName, s)); + } + return res; + } + + public static BigInteger coerceBigInteger(final String baseName, final String s) { + try { + return new BigInteger(s); + } catch (NumberFormatException e) { + throw new RuntimeException("Expected a number for request parameter '" + baseName + "'"); + } + } + + public static BigInteger coerceBigIntegerParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceBigInteger(baseName, s); + } + + public static List coerceBigIntegerArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceBigInteger(baseName, s)); + } + return res; + } + + public static Float coerceFloat(final String baseName, final String s) { + try { + return Float.valueOf(s); + } catch (NumberFormatException e) { + throw new RuntimeException("Expected a float for request parameter '" + baseName + "'"); + } + } + + public static Float coerceFloatParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceFloat(baseName, s); + } + + public static List coerceFloatArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceFloat(baseName, s)); + } + return res; + } + + public static Integer coerceInteger(final String baseName, final String s) { + try { + return Integer.valueOf(s); + } catch (NumberFormatException e) { + throw new RuntimeException("Expected an integer for request parameter '" + baseName + "'"); + } + } + + public static Integer coerceIntegerParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceInteger(baseName, s); + } + + public static List coerceIntegerArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceInteger(baseName, s)); + } + return res; + } + + public static Long coerceLong(final String baseName, final String s) { + try { + return Long.valueOf(s); + } catch (NumberFormatException e) { + throw new RuntimeException("Expected a long for request parameter '" + baseName + "'"); + } + } + + public static Long coerceLongParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceLong(baseName, s); + } + + public static List coerceLongArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceLong(baseName, s)); + } + return res; + } + + public static Short coerceShort(final String baseName, final String s) { + try { + return Short.valueOf(s); + } catch (NumberFormatException e) { + throw new RuntimeException("Expected a short for request parameter '" + baseName + "'"); + } + } + + public static Short coerceShortParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceShort(baseName, s); + } + + public static List coerceShortArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceShort(baseName, s)); + } + return res; + } + + public static Boolean coerceBoolean(final String baseName, final String s) { + if ("true".equals(s)) { + return true; + } else if ("false".equals(s)) { + return false; + } + throw new RuntimeException("Expected a boolean (true or false) for request parameter '" + baseName + "'"); + } + + public static Boolean coerceBooleanParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceBoolean(baseName, s); + } + + public static List coerceBooleanArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceBoolean(baseName, s)); + } + return res; + } + + public static OffsetDateTime coerceOffsetDateTime(final String baseName, final String s) { + try { + return OffsetDateTime.parse(s); + } catch (DateTimeException e) { + throw new RuntimeException("Expected a valid date (iso format) for request parameter '" + baseName + "'"); + } + } + + public static OffsetDateTime coerceOffsetDateTimeParameter(final String baseName, final boolean required, final Map parameters) { + Handlers.assertRequired(required, baseName, parameters); + String s = parameters.get(baseName); + return s == null ? null : coerceOffsetDateTime(baseName, s); + } + + public static List coerceOffsetDateTimeArrayParameter(final String baseName, final boolean required, final Map> parameters) { + Handlers.assertRequired(required, baseName, parameters); + List ss = parameters.get(baseName); + if (ss == null) { + return null; + } + List res = new ArrayList<>(); + for (String s : ss) { + res.add(coerceOffsetDateTime(baseName, s)); + } + return res; + } + + public static void putAllFromNullableMap(Map source, Map destination) { + if (source != null) { + destination.putAll(source); + } + } + + public static String concatMethodAndPath(final String method, final String path) { + return String.format("%s||%s", method.toLowerCase(), path); + } + + public static Map extractResponseHeadersFromInterceptors(final List> interceptors) { + Map headers = new HashMap<>(); + for (Interceptor interceptor : interceptors) { + if (interceptor instanceof ResponseHeadersInterceptor) { + headers.putAll(((ResponseHeadersInterceptor) interceptor).getAdditionalHeaders()); + } + } + return headers; + } + + public static List> getAnnotationInterceptors(Class clazz) { + // Support specifying simple interceptors via the @Interceptors({ MyInterceptor.class, MyOtherInterceptor.class }) format + return clazz.isAnnotationPresent(Interceptors.class) + ? Arrays.stream(clazz.getAnnotation(Interceptors.class).value()).map(c -> { + try { + return (Interceptor) c.getDeclaredConstructor().newInstance(); + } catch (Exception e) { + throw new RuntimeException(String.format( + "Cannot create instance of interceptor %s. Please ensure it has a public constructor " + + "with no arguments, or override the getInterceptors method instead of using the annotation", c.getSimpleName()), e); + } + }).collect(Collectors.toList()) + : new ArrayList<>(); + } + + public static HandlerChain buildHandlerChain(final List> interceptors, final HandlerChain baseChain) { + if (interceptors.isEmpty()) { + return baseChain; + } else { + Interceptor interceptor = interceptors.get(0); + HandlerChain remainingChain = buildHandlerChain(interceptors.subList(1, interceptors.size()), baseChain); + return new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return interceptor.handle(new ChainedRequestInput() { + @Override + public APIGatewayProxyRequestEvent getEvent() { + return input.getEvent(); + } + + @Override + public Context getContext() { + return input.getContext(); + } + + @Override + public TInput getInput() { + return input.getInput(); + } + + @Override + public HandlerChain getChain() { + return remainingChain; + } + + @Override + public Map getInterceptorContext() { + return input.getInterceptorContext(); + } + }); + } + }; + } + } +} +", + "src/main/java/test/test/runtime/api/handlers/Interceptor.java": " +package test.test.runtime.api.handlers; + +/** + * Interceptors can perform generic operations on requests and/or responses, optionally delegating to the remainder + * of the request chain. + */ +public interface Interceptor { + /** + * Handle a request. Usually the response from \`input.getChain().next(input)\` is returned to delegate to the + * remainder of the chain, however you may wish to return an alternative Response. + */ + Response handle(ChainedRequestInput input); +} +", + "src/main/java/test/test/runtime/api/handlers/InterceptorWarmupChainedRequestInput.java": " +package test.test.runtime.api.handlers; + +import com.amazonaws.services.lambda.runtime.ClientContext; +import com.amazonaws.services.lambda.runtime.CognitoIdentity; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; + +import java.util.HashMap; +import java.util.Map; +import java.util.List; + +/** + * An "empty" chained request input used to warm up interceptors which extend the InterceptorWithWarmup + */ +public class InterceptorWarmupChainedRequestInput implements ChainedRequestInput { + + @Override + public HandlerChain getChain() { + return new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return new Response() { + @Override + public String getBody() { + return ""; + } + + @Override + public int getStatusCode() { + return 0; + } + + @Override + public Map getHeaders() { + return new HashMap<>(); + } + + @Override + public Map> getMultiValueHeaders() { + return new HashMap<>(); + } + }; + } + }; + } + + @Override + public Context getContext() { + return new Context() { + @Override + public String getAwsRequestId() { + return ""; + } + + @Override + public String getLogGroupName() { + return ""; + } + + @Override + public String getLogStreamName() { + return ""; + } + + @Override + public String getFunctionName() { + return ""; + } + + @Override + public String getFunctionVersion() { + return ""; + } + + @Override + public String getInvokedFunctionArn() { + return ""; + } + + @Override + public CognitoIdentity getIdentity() { + return null; + } + + @Override + public ClientContext getClientContext() { + return null; + } + + @Override + public int getRemainingTimeInMillis() { + return 0; + } + + @Override + public int getMemoryLimitInMB() { + return 0; + } + + @Override + public LambdaLogger getLogger() { + return null; + } + }; + } + + @Override + public APIGatewayProxyRequestEvent getEvent() { + return new APIGatewayProxyRequestEvent(); + } + + @Override + public T getInput() { + return null; + } + + @Override + public Map getInterceptorContext() { + Map context = new HashMap<>(); + context.put("operationId", "__tsapi_interceptor_warmup"); + return context; + } +} +", + "src/main/java/test/test/runtime/api/handlers/InterceptorWithWarmup.java": " +package test.test.runtime.api.handlers; + +import org.crac.Resource; +import org.crac.Core; +import org.crac.Context; + +/** + * An interceptor with a "warmUp" method with default snap-start warmup behaviour, which can be overridden if desired. + */ +public abstract class InterceptorWithWarmup implements Interceptor, Resource { + { + Core.getGlobalContext().register(this); + } + + @Override + public void beforeCheckpoint(Context context) { + this.warmUp(); + } + + @Override + public void afterRestore(Context context) { + + } + + /** + * Called prior to the lambda snap-start snapshot. + * Override this to change the default behaviour, which is to call the interceptor's handle method with an empty + * chained request. + */ + public void warmUp() { + this.handle(new InterceptorWarmupChainedRequestInput<>()); + } +} +", + "src/main/java/test/test/runtime/api/handlers/Interceptors.java": " +package test.test.runtime.api.handlers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Use this annotation to add interceptors to the request handler. Interceptors used in the annotation must have a + * constructor with no arguments. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface Interceptors { + public Class[] value() default {}; +} +", + "src/main/java/test/test/runtime/api/handlers/RequestInput.java": " +package test.test.runtime.api.handlers; + +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.Context; +import java.util.Map; + +/** + * Defines the input for a request. + */ +public interface RequestInput { + /** + * The raw event from API Gateway + */ + APIGatewayProxyRequestEvent getEvent(); + /** + * Lambda execution context + */ + Context getContext(); + /** + * Demarshalled request input + */ + TInput getInput(); + /** + * Storage for arbitrary interceptor context for the lifetime of the request. Set and get values to pass state + * between interceptors or to the final handler. + */ + Map getInterceptorContext(); +} +", + "src/main/java/test/test/runtime/api/handlers/Response.java": " +package test.test.runtime.api.handlers; + +import java.util.Map; +import java.util.List; + +/** + * Represents an HTTP response from an api operation + */ +public interface Response { + /** + * Returns the response body + */ + String getBody(); + /** + * Returns the response status code + */ + int getStatusCode(); + /** + * Returns the response headers + */ + Map getHeaders(); + /** + * Returns the multi-value response headers + */ + Map> getMultiValueHeaders(); +} +", + "src/main/java/test/test/runtime/api/handlers/data_types/DataTypes.java": " +package test.test.runtime.api.handlers.data_types; + +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 dataTypes operation + */ +public abstract class DataTypes implements RequestHandler, Resource { + { + Core.getGlobalContext().register(this); + } + + /** + * Handle the request for the dataTypes operation + */ + public abstract DataTypesResponse handle(final DataTypesRequestInput request); + + /** + * Interceptors that the handler class has been decorated with + */ + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(DataTypes.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 DataTypesRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + } + }); + } + + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final DataTypesInput 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 DataTypesInput 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 DataTypesInput(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", "dataTypes"); + + List> interceptors = new ArrayList<>(); + interceptors.addAll(additionalInterceptors); + interceptors.addAll(this.getHandlerInterceptors()); + + final HandlerChain chain = this.buildChain(interceptors); + + DataTypesInput input; + + try { + input = new DataTypesInput(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/data_types/DataTypes200Response.java": " +package test.test.runtime.api.handlers.data_types; + +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 dataTypes operation + */ +public class DataTypes200Response extends RuntimeException implements DataTypesResponse { + 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 DataTypes200Response typedBody; + private final Map headers; + private final Map> multiValueHeaders; + + private DataTypes200Response(final DataTypes200Response 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 DataTypes200Response getTypedBody() { + return this.typedBody; + } + + @Override + public Map getHeaders() { + return this.headers; + } + + @Override + public Map> getMultiValueHeaders() { + return this.multiValueHeaders; + } + + /** + * Create a DataTypes200Response with a body + */ + public static DataTypes200Response of(final DataTypes200Response body) { + return new DataTypes200Response(body, new HashMap<>(), new HashMap<>()); + } + + /** + * Create a DataTypes200Response with a body and headers + */ + public static DataTypes200Response of(final DataTypes200Response body, final Map headers) { + return new DataTypes200Response(body, headers, new HashMap<>()); + } + + /** + * Create a DataTypes200Response with a body, headers and multi-value headers + */ + public static DataTypes200Response of(final DataTypes200Response body, final Map headers, final Map> multiValueHeaders) { + return new DataTypes200Response(body, headers, multiValueHeaders); + } +} +", + "src/main/java/test/test/runtime/api/handlers/data_types/DataTypesInput.java": " +package test.test.runtime.api.handlers.data_types; + +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 dataTypes operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class DataTypesInput { + 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 DataTypesRequestParameters requestParameters; + + public DataTypesInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new DataTypesRequestParameters(event); + } + + public DataTypesRequestParameters getRequestParameters() { + return this.requestParameters; + } + +} +", + "src/main/java/test/test/runtime/api/handlers/data_types/DataTypesRequestInput.java": " +package test.test.runtime.api.handlers.data_types; + +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 dataTypes operation, including the raw API Gateway event + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class DataTypesRequestInput implements RequestInput { + private final APIGatewayProxyRequestEvent event; + private final Context context; + private final Map interceptorContext; + private final DataTypesInput input; + + /** + * Returns the typed request input, with path, query and body parameters + */ + public DataTypesInput 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/data_types/DataTypesRequestParameters.java": " +package test.test.runtime.api.handlers.data_types; + +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 com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; + +/** + * Query, path and header parameters for the DataTypes operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class DataTypesRequestParameters { + + public DataTypesRequestParameters(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/data_types/DataTypesResponse.java": " +package test.test.runtime.api.handlers.data_types; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the dataTypes operation + */ +public interface DataTypesResponse 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 test.test.runtime.model.DataTypes200Response; + +import java.util.HashMap; +import java.util.Map; + +// Generic type for object "keyed" by operation names +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +@lombok.Builder @lombok.Getter +public class OperationConfig { + private T dataTypes; + + public Map asMap() { + Map map = new HashMap<>(); + map.put("dataTypes", this.dataTypes); + 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 test.test.runtime.model.DataTypes200Response; + +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 +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +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("dataTypes", OperationLookupEntry.builder() + .path("/types") + .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; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +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() + .dataTypes(value) + ; + } +} +", + "src/main/java/test/test/runtime/auth/ApiKeyAuth.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +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": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +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": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +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/DataTypes200Response.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.openapitools.jackson.nullable.JsonNullable; +import test.test.runtime.model.DataTypes200ResponseMyAllOf; +import test.test.runtime.model.DataTypes200ResponseMyAnyOf; +import test.test.runtime.model.DataTypes200ResponseMyObject; +import test.test.runtime.model.DataTypes200ResponseMyOneOf; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * DataTypes200Response + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DataTypes200Response { + public static final String SERIALIZED_NAME_MY_INT = "myInt"; + @SerializedName(SERIALIZED_NAME_MY_INT) + private Integer myInt; + + public static final String SERIALIZED_NAME_MY_STRING = "myString"; + @SerializedName(SERIALIZED_NAME_MY_STRING) + private String myString; + + public static final String SERIALIZED_NAME_MY_STRING_LENGTH = "myStringLength"; + @SerializedName(SERIALIZED_NAME_MY_STRING_LENGTH) + private String myStringLength; + + public static final String SERIALIZED_NAME_MY_LONG_MIN_STRING_LENGTH = "myLongMinStringLength"; + @SerializedName(SERIALIZED_NAME_MY_LONG_MIN_STRING_LENGTH) + private String myLongMinStringLength; + + public static final String SERIALIZED_NAME_MY_BOOL = "myBool"; + @SerializedName(SERIALIZED_NAME_MY_BOOL) + private Boolean myBool; + + public static final String SERIALIZED_NAME_MY_NUMBER = "myNumber"; + @SerializedName(SERIALIZED_NAME_MY_NUMBER) + private BigDecimal myNumber; + + public static final String SERIALIZED_NAME_MY_DATE_ARRAY = "myDateArray"; + @SerializedName(SERIALIZED_NAME_MY_DATE_ARRAY) + private List myDateArray = null; + + public static final String SERIALIZED_NAME_MY_EMAIL = "myEmail"; + @SerializedName(SERIALIZED_NAME_MY_EMAIL) + private String myEmail; + + public static final String SERIALIZED_NAME_MY_URL = "myUrl"; + @SerializedName(SERIALIZED_NAME_MY_URL) + private URI myUrl; + + public static final String SERIALIZED_NAME_MY_HOSTNAME = "myHostname"; + @SerializedName(SERIALIZED_NAME_MY_HOSTNAME) + private String myHostname; + + public static final String SERIALIZED_NAME_MY_IPV4 = "myIpv4"; + @SerializedName(SERIALIZED_NAME_MY_IPV4) + private String myIpv4; + + public static final String SERIALIZED_NAME_MY_IPV6 = "myIpv6"; + @SerializedName(SERIALIZED_NAME_MY_IPV6) + private String myIpv6; + + public static final String SERIALIZED_NAME_MY_UUID = "myUuid"; + @SerializedName(SERIALIZED_NAME_MY_UUID) + private UUID myUuid; + + public static final String SERIALIZED_NAME_MY_BYTE = "myByte"; + @SerializedName(SERIALIZED_NAME_MY_BYTE) + private byte[] myByte; + + public static final String SERIALIZED_NAME_MY_DATE_TIME = "myDateTime"; + @SerializedName(SERIALIZED_NAME_MY_DATE_TIME) + private OffsetDateTime myDateTime; + + public static final String SERIALIZED_NAME_MY_REGEX_PATTERN = "myRegexPattern"; + @SerializedName(SERIALIZED_NAME_MY_REGEX_PATTERN) + private String myRegexPattern; + + public static final String SERIALIZED_NAME_MY_ONE_OF = "myOneOf"; + @SerializedName(SERIALIZED_NAME_MY_ONE_OF) + private DataTypes200ResponseMyOneOf myOneOf; + + public static final String SERIALIZED_NAME_MY_ANY_OF = "myAnyOf"; + @SerializedName(SERIALIZED_NAME_MY_ANY_OF) + private DataTypes200ResponseMyAnyOf myAnyOf; + + public static final String SERIALIZED_NAME_MY_ALL_OF = "myAllOf"; + @SerializedName(SERIALIZED_NAME_MY_ALL_OF) + private DataTypes200ResponseMyAllOf myAllOf; + + public static final String SERIALIZED_NAME_MY_NOT = "myNot"; + @SerializedName(SERIALIZED_NAME_MY_NOT) + private Object myNot = null; + + public static final String SERIALIZED_NAME_MY_NOT_STRING = "myNotString"; + @SerializedName(SERIALIZED_NAME_MY_NOT_STRING) + private Object myNotString = null; + + public static final String SERIALIZED_NAME_MY_ADDITIONAL_PROPERTIES = "myAdditionalProperties"; + @SerializedName(SERIALIZED_NAME_MY_ADDITIONAL_PROPERTIES) + private Map> myAdditionalProperties = null; + + public static final String SERIALIZED_NAME_MY_OBJECT = "myObject"; + @SerializedName(SERIALIZED_NAME_MY_OBJECT) + private DataTypes200ResponseMyObject myObject; + + public DataTypes200Response() { + } + + public DataTypes200Response myInt(Integer myInt) { + + this.myInt = myInt; + return this; + } + + /** + * Get myInt + * minimum: 3 + * maximum: 7 + * @return myInt + **/ + @javax.annotation.Nullable + + public Integer getMyInt() { + return myInt; + } + + + public void setMyInt(Integer myInt) { + this.myInt = myInt; + } + + + public DataTypes200Response myString(String myString) { + + this.myString = myString; + return this; + } + + /** + * Get myString + * @return myString + **/ + @javax.annotation.Nullable + + public String getMyString() { + return myString; + } + + + public void setMyString(String myString) { + this.myString = myString; + } + + + public DataTypes200Response myStringLength(String myStringLength) { + + this.myStringLength = myStringLength; + return this; + } + + /** + * Get myStringLength + * @return myStringLength + **/ + @javax.annotation.Nullable + + public String getMyStringLength() { + return myStringLength; + } + + + public void setMyStringLength(String myStringLength) { + this.myStringLength = myStringLength; + } + + + public DataTypes200Response myLongMinStringLength(String myLongMinStringLength) { + + this.myLongMinStringLength = myLongMinStringLength; + return this; + } + + /** + * Get myLongMinStringLength + * @return myLongMinStringLength + **/ + @javax.annotation.Nullable + + public String getMyLongMinStringLength() { + return myLongMinStringLength; + } + + + public void setMyLongMinStringLength(String myLongMinStringLength) { + this.myLongMinStringLength = myLongMinStringLength; + } + + + public DataTypes200Response myBool(Boolean myBool) { + + this.myBool = myBool; + return this; + } + + /** + * Get myBool + * @return myBool + **/ + @javax.annotation.Nullable + + public Boolean getMyBool() { + return myBool; + } + + + public void setMyBool(Boolean myBool) { + this.myBool = myBool; + } + + + public DataTypes200Response myNumber(BigDecimal myNumber) { + + this.myNumber = myNumber; + return this; + } + + /** + * Get myNumber + * @return myNumber + **/ + @javax.annotation.Nullable + + public BigDecimal getMyNumber() { + return myNumber; + } + + + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + + public DataTypes200Response myDateArray(List myDateArray) { + + this.myDateArray = myDateArray; + return this; + } + + public DataTypes200Response addMyDateArrayItem(LocalDate myDateArrayItem) { + if (this.myDateArray == null) { + this.myDateArray = new ArrayList<>(); + } + this.myDateArray.add(myDateArrayItem); + return this; + } + + /** + * Get myDateArray + * @return myDateArray + **/ + @javax.annotation.Nullable + + public List getMyDateArray() { + return myDateArray; + } + + + public void setMyDateArray(List myDateArray) { + this.myDateArray = myDateArray; + } + + + public DataTypes200Response myEmail(String myEmail) { + + this.myEmail = myEmail; + return this; + } + + /** + * Get myEmail + * @return myEmail + **/ + @javax.annotation.Nullable + + public String getMyEmail() { + return myEmail; + } + + + public void setMyEmail(String myEmail) { + this.myEmail = myEmail; + } + + + public DataTypes200Response myUrl(URI myUrl) { + + this.myUrl = myUrl; + return this; + } + + /** + * Get myUrl + * @return myUrl + **/ + @javax.annotation.Nullable + + public URI getMyUrl() { + return myUrl; + } + + + public void setMyUrl(URI myUrl) { + this.myUrl = myUrl; + } + + + public DataTypes200Response myHostname(String myHostname) { + + this.myHostname = myHostname; + return this; + } + + /** + * Get myHostname + * @return myHostname + **/ + @javax.annotation.Nullable + + public String getMyHostname() { + return myHostname; + } + + + public void setMyHostname(String myHostname) { + this.myHostname = myHostname; + } + + + public DataTypes200Response myIpv4(String myIpv4) { + + this.myIpv4 = myIpv4; + return this; + } + + /** + * Get myIpv4 + * @return myIpv4 + **/ + @javax.annotation.Nullable + + public String getMyIpv4() { + return myIpv4; + } + + + public void setMyIpv4(String myIpv4) { + this.myIpv4 = myIpv4; + } + + + public DataTypes200Response myIpv6(String myIpv6) { + + this.myIpv6 = myIpv6; + return this; + } + + /** + * Get myIpv6 + * @return myIpv6 + **/ + @javax.annotation.Nullable + + public String getMyIpv6() { + return myIpv6; + } + + + public void setMyIpv6(String myIpv6) { + this.myIpv6 = myIpv6; + } + + + public DataTypes200Response myUuid(UUID myUuid) { + + this.myUuid = myUuid; + return this; + } + + /** + * Get myUuid + * @return myUuid + **/ + @javax.annotation.Nullable + + public UUID getMyUuid() { + return myUuid; + } + + + public void setMyUuid(UUID myUuid) { + this.myUuid = myUuid; + } + + + public DataTypes200Response myByte(byte[] myByte) { + + this.myByte = myByte; + return this; + } + + /** + * Get myByte + * @return myByte + **/ + @javax.annotation.Nullable + + public byte[] getMyByte() { + return myByte; + } + + + public void setMyByte(byte[] myByte) { + this.myByte = myByte; + } + + + public DataTypes200Response myDateTime(OffsetDateTime myDateTime) { + + this.myDateTime = myDateTime; + return this; + } + + /** + * Get myDateTime + * @return myDateTime + **/ + @javax.annotation.Nullable + + public OffsetDateTime getMyDateTime() { + return myDateTime; + } + + + public void setMyDateTime(OffsetDateTime myDateTime) { + this.myDateTime = myDateTime; + } + + + public DataTypes200Response myRegexPattern(String myRegexPattern) { + + this.myRegexPattern = myRegexPattern; + return this; + } + + /** + * Get myRegexPattern + * @return myRegexPattern + **/ + @javax.annotation.Nullable + + public String getMyRegexPattern() { + return myRegexPattern; + } + + + public void setMyRegexPattern(String myRegexPattern) { + this.myRegexPattern = myRegexPattern; + } + + + public DataTypes200Response myOneOf(DataTypes200ResponseMyOneOf myOneOf) { + + this.myOneOf = myOneOf; + return this; + } + + /** + * Get myOneOf + * @return myOneOf + **/ + @javax.annotation.Nullable + + public DataTypes200ResponseMyOneOf getMyOneOf() { + return myOneOf; + } + + + public void setMyOneOf(DataTypes200ResponseMyOneOf myOneOf) { + this.myOneOf = myOneOf; + } + + + public DataTypes200Response myAnyOf(DataTypes200ResponseMyAnyOf myAnyOf) { + + this.myAnyOf = myAnyOf; + return this; + } + + /** + * Get myAnyOf + * @return myAnyOf + **/ + @javax.annotation.Nullable + + public DataTypes200ResponseMyAnyOf getMyAnyOf() { + return myAnyOf; + } + + + public void setMyAnyOf(DataTypes200ResponseMyAnyOf myAnyOf) { + this.myAnyOf = myAnyOf; + } + + + public DataTypes200Response myAllOf(DataTypes200ResponseMyAllOf myAllOf) { + + this.myAllOf = myAllOf; + return this; + } + + /** + * Get myAllOf + * @return myAllOf + **/ + @javax.annotation.Nullable + + public DataTypes200ResponseMyAllOf getMyAllOf() { + return myAllOf; + } + + + public void setMyAllOf(DataTypes200ResponseMyAllOf myAllOf) { + this.myAllOf = myAllOf; + } + + + public DataTypes200Response myNot(Object myNot) { + + this.myNot = myNot; + return this; + } + + /** + * Get myNot + * @return myNot + **/ + @javax.annotation.Nullable + + public Object getMyNot() { + return myNot; + } + + + public void setMyNot(Object myNot) { + this.myNot = myNot; + } + + + public DataTypes200Response myNotString(Object myNotString) { + + this.myNotString = myNotString; + return this; + } + + /** + * Get myNotString + * @return myNotString + **/ + @javax.annotation.Nullable + + public Object getMyNotString() { + return myNotString; + } + + + public void setMyNotString(Object myNotString) { + this.myNotString = myNotString; + } + + + public DataTypes200Response myAdditionalProperties(Map> myAdditionalProperties) { + + this.myAdditionalProperties = myAdditionalProperties; + return this; + } + + public DataTypes200Response putMyAdditionalPropertiesItem(String key, List myAdditionalPropertiesItem) { + if (this.myAdditionalProperties == null) { + this.myAdditionalProperties = new HashMap<>(); + } + this.myAdditionalProperties.put(key, myAdditionalPropertiesItem); + return this; + } + + /** + * Get myAdditionalProperties + * @return myAdditionalProperties + **/ + @javax.annotation.Nullable + + public Map> getMyAdditionalProperties() { + return myAdditionalProperties; + } + + + public void setMyAdditionalProperties(Map> myAdditionalProperties) { + this.myAdditionalProperties = myAdditionalProperties; + } + + + public DataTypes200Response myObject(DataTypes200ResponseMyObject myObject) { + + this.myObject = myObject; + return this; + } + + /** + * Get myObject + * @return myObject + **/ + @javax.annotation.Nullable + + public DataTypes200ResponseMyObject getMyObject() { + return myObject; + } + + + public void setMyObject(DataTypes200ResponseMyObject myObject) { + this.myObject = myObject; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DataTypes200Response dataTypes200Response = (DataTypes200Response) o; + return Objects.equals(this.myInt, dataTypes200Response.myInt) && + Objects.equals(this.myString, dataTypes200Response.myString) && + Objects.equals(this.myStringLength, dataTypes200Response.myStringLength) && + Objects.equals(this.myLongMinStringLength, dataTypes200Response.myLongMinStringLength) && + Objects.equals(this.myBool, dataTypes200Response.myBool) && + Objects.equals(this.myNumber, dataTypes200Response.myNumber) && + Objects.equals(this.myDateArray, dataTypes200Response.myDateArray) && + Objects.equals(this.myEmail, dataTypes200Response.myEmail) && + Objects.equals(this.myUrl, dataTypes200Response.myUrl) && + Objects.equals(this.myHostname, dataTypes200Response.myHostname) && + Objects.equals(this.myIpv4, dataTypes200Response.myIpv4) && + Objects.equals(this.myIpv6, dataTypes200Response.myIpv6) && + Objects.equals(this.myUuid, dataTypes200Response.myUuid) && + Arrays.equals(this.myByte, dataTypes200Response.myByte) && + Objects.equals(this.myDateTime, dataTypes200Response.myDateTime) && + Objects.equals(this.myRegexPattern, dataTypes200Response.myRegexPattern) && + Objects.equals(this.myOneOf, dataTypes200Response.myOneOf) && + Objects.equals(this.myAnyOf, dataTypes200Response.myAnyOf) && + Objects.equals(this.myAllOf, dataTypes200Response.myAllOf) && + Objects.equals(this.myNot, dataTypes200Response.myNot) && + Objects.equals(this.myNotString, dataTypes200Response.myNotString) && + Objects.equals(this.myAdditionalProperties, dataTypes200Response.myAdditionalProperties) && + Objects.equals(this.myObject, dataTypes200Response.myObject); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(myInt, myString, myStringLength, myLongMinStringLength, myBool, myNumber, myDateArray, myEmail, myUrl, myHostname, myIpv4, myIpv6, myUuid, Arrays.hashCode(myByte), myDateTime, myRegexPattern, myOneOf, myAnyOf, myAllOf, myNot, myNotString, myAdditionalProperties, myObject); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DataTypes200Response {\\n"); + sb.append(" myInt: ").append(toIndentedString(myInt)).append("\\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\\n"); + sb.append(" myStringLength: ").append(toIndentedString(myStringLength)).append("\\n"); + sb.append(" myLongMinStringLength: ").append(toIndentedString(myLongMinStringLength)).append("\\n"); + sb.append(" myBool: ").append(toIndentedString(myBool)).append("\\n"); + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\\n"); + sb.append(" myDateArray: ").append(toIndentedString(myDateArray)).append("\\n"); + sb.append(" myEmail: ").append(toIndentedString(myEmail)).append("\\n"); + sb.append(" myUrl: ").append(toIndentedString(myUrl)).append("\\n"); + sb.append(" myHostname: ").append(toIndentedString(myHostname)).append("\\n"); + sb.append(" myIpv4: ").append(toIndentedString(myIpv4)).append("\\n"); + sb.append(" myIpv6: ").append(toIndentedString(myIpv6)).append("\\n"); + sb.append(" myUuid: ").append(toIndentedString(myUuid)).append("\\n"); + sb.append(" myByte: ").append(toIndentedString(myByte)).append("\\n"); + sb.append(" myDateTime: ").append(toIndentedString(myDateTime)).append("\\n"); + sb.append(" myRegexPattern: ").append(toIndentedString(myRegexPattern)).append("\\n"); + sb.append(" myOneOf: ").append(toIndentedString(myOneOf)).append("\\n"); + sb.append(" myAnyOf: ").append(toIndentedString(myAnyOf)).append("\\n"); + sb.append(" myAllOf: ").append(toIndentedString(myAllOf)).append("\\n"); + sb.append(" myNot: ").append(toIndentedString(myNot)).append("\\n"); + sb.append(" myNotString: ").append(toIndentedString(myNotString)).append("\\n"); + sb.append(" myAdditionalProperties: ").append(toIndentedString(myAdditionalProperties)).append("\\n"); + sb.append(" myObject: ").append(toIndentedString(myObject)).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("myInt"); + openapiFields.add("myString"); + openapiFields.add("myStringLength"); + openapiFields.add("myLongMinStringLength"); + openapiFields.add("myBool"); + openapiFields.add("myNumber"); + openapiFields.add("myDateArray"); + openapiFields.add("myEmail"); + openapiFields.add("myUrl"); + openapiFields.add("myHostname"); + openapiFields.add("myIpv4"); + openapiFields.add("myIpv6"); + openapiFields.add("myUuid"); + openapiFields.add("myByte"); + openapiFields.add("myDateTime"); + openapiFields.add("myRegexPattern"); + openapiFields.add("myOneOf"); + openapiFields.add("myAnyOf"); + openapiFields.add("myAllOf"); + openapiFields.add("myNot"); + openapiFields.add("myNotString"); + openapiFields.add("myAdditionalProperties"); + openapiFields.add("myObject"); + + // 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 DataTypes200Response + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!DataTypes200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200Response is not found in the empty JSON string", DataTypes200Response.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!DataTypes200Response.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200Response\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("myString") != null && !jsonObj.get("myString").isJsonNull()) && !jsonObj.get("myString").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myString\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myString").toString())); + } + if ((jsonObj.get("myStringLength") != null && !jsonObj.get("myStringLength").isJsonNull()) && !jsonObj.get("myStringLength").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myStringLength\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myStringLength").toString())); + } + if ((jsonObj.get("myLongMinStringLength") != null && !jsonObj.get("myLongMinStringLength").isJsonNull()) && !jsonObj.get("myLongMinStringLength").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myLongMinStringLength\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myLongMinStringLength").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("myDateArray") != null && !jsonObj.get("myDateArray").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field \`myDateArray\` to be an array in the JSON string but got \`%s\`", jsonObj.get("myDateArray").toString())); + } + if ((jsonObj.get("myEmail") != null && !jsonObj.get("myEmail").isJsonNull()) && !jsonObj.get("myEmail").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myEmail\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myEmail").toString())); + } + if ((jsonObj.get("myUrl") != null && !jsonObj.get("myUrl").isJsonNull()) && !jsonObj.get("myUrl").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myUrl\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myUrl").toString())); + } + if ((jsonObj.get("myHostname") != null && !jsonObj.get("myHostname").isJsonNull()) && !jsonObj.get("myHostname").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myHostname\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myHostname").toString())); + } + if ((jsonObj.get("myIpv4") != null && !jsonObj.get("myIpv4").isJsonNull()) && !jsonObj.get("myIpv4").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myIpv4\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myIpv4").toString())); + } + if ((jsonObj.get("myIpv6") != null && !jsonObj.get("myIpv6").isJsonNull()) && !jsonObj.get("myIpv6").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myIpv6\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myIpv6").toString())); + } + if ((jsonObj.get("myUuid") != null && !jsonObj.get("myUuid").isJsonNull()) && !jsonObj.get("myUuid").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myUuid\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myUuid").toString())); + } + if ((jsonObj.get("myRegexPattern") != null && !jsonObj.get("myRegexPattern").isJsonNull()) && !jsonObj.get("myRegexPattern").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`myRegexPattern\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("myRegexPattern").toString())); + } + // validate the optional field \`myOneOf\` + if (jsonObj.get("myOneOf") != null && !jsonObj.get("myOneOf").isJsonNull()) { + DataTypes200ResponseMyOneOf.validateJsonObject(jsonObj.getAsJsonObject("myOneOf")); + } + // validate the optional field \`myAnyOf\` + if (jsonObj.get("myAnyOf") != null && !jsonObj.get("myAnyOf").isJsonNull()) { + DataTypes200ResponseMyAnyOf.validateJsonObject(jsonObj.getAsJsonObject("myAnyOf")); + } + // validate the optional field \`myAllOf\` + if (jsonObj.get("myAllOf") != null && !jsonObj.get("myAllOf").isJsonNull()) { + DataTypes200ResponseMyAllOf.validateJsonObject(jsonObj.getAsJsonObject("myAllOf")); + } + // validate the optional field \`myObject\` + if (jsonObj.get("myObject") != null && !jsonObj.get("myObject").isJsonNull()) { + DataTypes200ResponseMyObject.validateJsonObject(jsonObj.getAsJsonObject("myObject")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DataTypes200Response.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200Response' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200Response.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DataTypes200Response value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DataTypes200Response read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of DataTypes200Response given an JSON string + * + * @param jsonString JSON string + * @return An instance of DataTypes200Response + * @throws IOException if the JSON string is invalid with respect to DataTypes200Response + */ + public static DataTypes200Response fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200Response.class); + } + + /** + * Convert an instance of DataTypes200Response to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOf.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * DataTypes200ResponseMyAllOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DataTypes200ResponseMyAllOf { + public static final String SERIALIZED_NAME_FIRST = "first"; + @SerializedName(SERIALIZED_NAME_FIRST) + private String first; + + public static final String SERIALIZED_NAME_SECOND = "second"; + @SerializedName(SERIALIZED_NAME_SECOND) + private String second; + + public DataTypes200ResponseMyAllOf() { + } + + public DataTypes200ResponseMyAllOf first(String first) { + + this.first = first; + return this; + } + + /** + * Get first + * @return first + **/ + @javax.annotation.Nullable + + public String getFirst() { + return first; + } + + + public void setFirst(String first) { + this.first = first; + } + + + public DataTypes200ResponseMyAllOf second(String second) { + + this.second = second; + return this; + } + + /** + * Get second + * @return second + **/ + @javax.annotation.Nullable + + public String getSecond() { + return second; + } + + + public void setSecond(String second) { + this.second = second; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DataTypes200ResponseMyAllOf dataTypes200ResponseMyAllOf = (DataTypes200ResponseMyAllOf) o; + return Objects.equals(this.first, dataTypes200ResponseMyAllOf.first) && + Objects.equals(this.second, dataTypes200ResponseMyAllOf.second); + } + + @Override + public int hashCode() { + return Objects.hash(first, second); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DataTypes200ResponseMyAllOf {\\n"); + sb.append(" first: ").append(toIndentedString(first)).append("\\n"); + sb.append(" second: ").append(toIndentedString(second)).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("first"); + openapiFields.add("second"); + + // 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 DataTypes200ResponseMyAllOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!DataTypes200ResponseMyAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyAllOf is not found in the empty JSON string", DataTypes200ResponseMyAllOf.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!DataTypes200ResponseMyAllOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyAllOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("first") != null && !jsonObj.get("first").isJsonNull()) && !jsonObj.get("first").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`first\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("first").toString())); + } + if ((jsonObj.get("second") != null && !jsonObj.get("second").isJsonNull()) && !jsonObj.get("second").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`second\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("second").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DataTypes200ResponseMyAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyAllOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DataTypes200ResponseMyAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DataTypes200ResponseMyAllOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of DataTypes200ResponseMyAllOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of DataTypes200ResponseMyAllOf + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAllOf + */ + public static DataTypes200ResponseMyAllOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAllOf.class); + } + + /** + * Convert an instance of DataTypes200ResponseMyAllOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * DataTypes200ResponseMyAllOfAllOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DataTypes200ResponseMyAllOfAllOf { + public static final String SERIALIZED_NAME_FIRST = "first"; + @SerializedName(SERIALIZED_NAME_FIRST) + private String first; + + public DataTypes200ResponseMyAllOfAllOf() { + } + + public DataTypes200ResponseMyAllOfAllOf first(String first) { + + this.first = first; + return this; + } + + /** + * Get first + * @return first + **/ + @javax.annotation.Nullable + + public String getFirst() { + return first; + } + + + public void setFirst(String first) { + this.first = first; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DataTypes200ResponseMyAllOfAllOf dataTypes200ResponseMyAllOfAllOf = (DataTypes200ResponseMyAllOfAllOf) o; + return Objects.equals(this.first, dataTypes200ResponseMyAllOfAllOf.first); + } + + @Override + public int hashCode() { + return Objects.hash(first); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DataTypes200ResponseMyAllOfAllOf {\\n"); + sb.append(" first: ").append(toIndentedString(first)).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("first"); + + // 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 DataTypes200ResponseMyAllOfAllOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!DataTypes200ResponseMyAllOfAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyAllOfAllOf is not found in the empty JSON string", DataTypes200ResponseMyAllOfAllOf.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!DataTypes200ResponseMyAllOfAllOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyAllOfAllOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("first") != null && !jsonObj.get("first").isJsonNull()) && !jsonObj.get("first").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`first\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("first").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DataTypes200ResponseMyAllOfAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyAllOfAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyAllOfAllOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DataTypes200ResponseMyAllOfAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DataTypes200ResponseMyAllOfAllOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of DataTypes200ResponseMyAllOfAllOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of DataTypes200ResponseMyAllOfAllOf + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAllOfAllOf + */ + public static DataTypes200ResponseMyAllOfAllOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAllOfAllOf.class); + } + + /** + * Convert an instance of DataTypes200ResponseMyAllOfAllOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf1.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * 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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import test.test.runtime.JSON; + +/** + * DataTypes200ResponseMyAllOfAllOf1 + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DataTypes200ResponseMyAllOfAllOf1 { + public static final String SERIALIZED_NAME_SECOND = "second"; + @SerializedName(SERIALIZED_NAME_SECOND) + private String second; + + public DataTypes200ResponseMyAllOfAllOf1() { + } + + public DataTypes200ResponseMyAllOfAllOf1 second(String second) { + + this.second = second; + return this; + } + + /** + * Get second + * @return second + **/ + @javax.annotation.Nullable + + public String getSecond() { + return second; + } + + + public void setSecond(String second) { + this.second = second; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DataTypes200ResponseMyAllOfAllOf1 dataTypes200ResponseMyAllOfAllOf1 = (DataTypes200ResponseMyAllOfAllOf1) o; + return Objects.equals(this.second, dataTypes200ResponseMyAllOfAllOf1.second); + } + + @Override + public int hashCode() { + return Objects.hash(second); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DataTypes200ResponseMyAllOfAllOf1 {\\n"); + sb.append(" second: ").append(toIndentedString(second)).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("second"); + + // 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 DataTypes200ResponseMyAllOfAllOf1 + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!DataTypes200ResponseMyAllOfAllOf1.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyAllOfAllOf1 is not found in the empty JSON string", DataTypes200ResponseMyAllOfAllOf1.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!DataTypes200ResponseMyAllOfAllOf1.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyAllOfAllOf1\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("second") != null && !jsonObj.get("second").isJsonNull()) && !jsonObj.get("second").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`second\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("second").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DataTypes200ResponseMyAllOfAllOf1.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyAllOfAllOf1' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyAllOfAllOf1.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DataTypes200ResponseMyAllOfAllOf1 value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DataTypes200ResponseMyAllOfAllOf1 read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of DataTypes200ResponseMyAllOfAllOf1 given an JSON string + * + * @param jsonString JSON string + * @return An instance of DataTypes200ResponseMyAllOfAllOf1 + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAllOfAllOf1 + */ + public static DataTypes200ResponseMyAllOfAllOf1 fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAllOfAllOf1.class); + } + + /** + * Convert an instance of DataTypes200ResponseMyAllOfAllOf1 to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + +", + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAnyOf.java": "/* + * Data Types + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import java.math.BigDecimal; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; +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; + +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DataTypes200ResponseMyAnyOf extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(DataTypes200ResponseMyAnyOf.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DataTypes200ResponseMyAnyOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyAnyOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterBigDecimal = gson.getDelegateAdapter(this, TypeToken.get(BigDecimal.class)); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DataTypes200ResponseMyAnyOf value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type \`BigDecimal\` + if (value.getActualInstance() instanceof BigDecimal) { + JsonObject obj = adapterBigDecimal.toJsonTree((BigDecimal)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + // check if the actual instance is of the type \`String\` + if (value.getActualInstance() instanceof String) { + JsonObject obj = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } + + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: BigDecimal, String"); + } + + @Override + public DataTypes200ResponseMyAnyOf read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + // deserialize BigDecimal + try { + // validate the JSON object to see if any exception is thrown + BigDecimal.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'BigDecimal'"); + DataTypes200ResponseMyAnyOf ret = new DataTypes200ResponseMyAnyOf(); + ret.setActualInstance(adapterBigDecimal.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'BigDecimal'", e); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + String.validateJsonObject(jsonObject); + log.log(Level.FINER, "Input data matches schema 'String'"); + DataTypes200ResponseMyAnyOf ret = new DataTypes200ResponseMyAnyOf(); + ret.setActualInstance(adapterString.fromJsonTree(jsonObject)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + + throw new IOException(String.format("Failed deserialization for DataTypes200ResponseMyAnyOf: no class matched. JSON: %s", jsonObject.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map schemas = new HashMap(); + + public DataTypes200ResponseMyAnyOf() { + super("anyOf", Boolean.FALSE); + } + + public DataTypes200ResponseMyAnyOf(BigDecimal o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public DataTypes200ResponseMyAnyOf(String o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("BigDecimal", new GenericType() { + }); + schemas.put("String", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return DataTypes200ResponseMyAnyOf.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * BigDecimal, String + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof BigDecimal) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be BigDecimal, String"); + } + + /** + * Get the actual instance, which can be the following: + * BigDecimal, String + * + * @return The actual instance (BigDecimal, String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`BigDecimal\`. If the actual instance is not \`BigDecimal\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`BigDecimal\` + * @throws ClassCastException if the instance is not \`BigDecimal\` + */ + public BigDecimal getBigDecimal() throws ClassCastException { + return (BigDecimal)super.getActualInstance(); + } + + /** + * Get the actual instance of \`String\`. If the actual instance is not \`String\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`String\` + * @throws ClassCastException if the instance is not \`String\` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + + /** + * 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 DataTypes200ResponseMyAnyOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + // validate anyOf schemas one by one + int validCount = 0; + // validate the json string with BigDecimal + try { + BigDecimal.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + // validate the json string with String + try { + String.validateJsonObject(jsonObj); + return; // return earlier as at least one schema is valid with respect to the Json object + //validCount++; + } catch (Exception e) { + // continue to the next one + } + if (validCount == 0) { + throw new IOException(String.format("The JSON string is invalid for DataTypes200ResponseMyAnyOf with anyOf schemas: BigDecimal, String. JSON: %s", jsonObj.toString())); } } /** - * Create an instance of DataTypes200ResponseMyAllOf given an JSON string + * Create an instance of DataTypes200ResponseMyAnyOf given an JSON string * * @param jsonString JSON string - * @return An instance of DataTypes200ResponseMyAllOf - * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAllOf + * @return An instance of DataTypes200ResponseMyAnyOf + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAnyOf */ - public static DataTypes200ResponseMyAllOf fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAllOf.class); + public static DataTypes200ResponseMyAnyOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAnyOf.class); } /** - * Convert an instance of DataTypes200ResponseMyAllOf to an JSON string + * Convert an instance of DataTypes200ResponseMyAnyOf to an JSON string * * @return JSON string */ @@ -12932,7 +25082,7 @@ public class DataTypes200ResponseMyAllOf { } ", - "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf.java": "/* + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyNotNot.java": "/* * Data Types * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * @@ -12978,37 +25128,37 @@ import java.util.Set; import test.test.runtime.JSON; /** - * DataTypes200ResponseMyAllOfAllOf + * DataTypes200ResponseMyNotNot */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DataTypes200ResponseMyAllOfAllOf { - public static final String SERIALIZED_NAME_FIRST = "first"; - @SerializedName(SERIALIZED_NAME_FIRST) - private String first; +public class DataTypes200ResponseMyNotNot { + public static final String SERIALIZED_NAME_FOO = "foo"; + @SerializedName(SERIALIZED_NAME_FOO) + private String foo; - public DataTypes200ResponseMyAllOfAllOf() { + public DataTypes200ResponseMyNotNot() { } - public DataTypes200ResponseMyAllOfAllOf first(String first) { + public DataTypes200ResponseMyNotNot foo(String foo) { - this.first = first; + this.foo = foo; return this; } /** - * Get first - * @return first + * Get foo + * @return foo **/ @javax.annotation.Nullable - public String getFirst() { - return first; + public String getFoo() { + return foo; } - public void setFirst(String first) { - this.first = first; + public void setFoo(String foo) { + this.foo = foo; } @@ -13021,20 +25171,20 @@ public class DataTypes200ResponseMyAllOfAllOf { if (o == null || getClass() != o.getClass()) { return false; } - DataTypes200ResponseMyAllOfAllOf dataTypes200ResponseMyAllOfAllOf = (DataTypes200ResponseMyAllOfAllOf) o; - return Objects.equals(this.first, dataTypes200ResponseMyAllOfAllOf.first); + DataTypes200ResponseMyNotNot dataTypes200ResponseMyNotNot = (DataTypes200ResponseMyNotNot) o; + return Objects.equals(this.foo, dataTypes200ResponseMyNotNot.foo); } @Override public int hashCode() { - return Objects.hash(first); + return Objects.hash(foo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class DataTypes200ResponseMyAllOfAllOf {\\n"); - sb.append(" first: ").append(toIndentedString(first)).append("\\n"); + sb.append("class DataTypes200ResponseMyNotNot {\\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -13057,7 +25207,7 @@ public class DataTypes200ResponseMyAllOfAllOf { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("first"); + openapiFields.add("foo"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); @@ -13067,24 +25217,24 @@ public class DataTypes200ResponseMyAllOfAllOf { * 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 DataTypes200ResponseMyAllOfAllOf + * @throws IOException if the JSON Object is invalid with respect to DataTypes200ResponseMyNotNot */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!DataTypes200ResponseMyAllOfAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyAllOfAllOf is not found in the empty JSON string", DataTypes200ResponseMyAllOfAllOf.openapiRequiredFields.toString())); + if (!DataTypes200ResponseMyNotNot.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyNotNot is not found in the empty JSON string", DataTypes200ResponseMyNotNot.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!DataTypes200ResponseMyAllOfAllOf.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyAllOfAllOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!DataTypes200ResponseMyNotNot.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyNotNot\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if ((jsonObj.get("first") != null && !jsonObj.get("first").isJsonNull()) && !jsonObj.get("first").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`first\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("first").toString())); + 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())); } } @@ -13092,22 +25242,22 @@ public class DataTypes200ResponseMyAllOfAllOf { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!DataTypes200ResponseMyAllOfAllOf.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DataTypes200ResponseMyAllOfAllOf' and its subtypes + if (!DataTypes200ResponseMyNotNot.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyNotNot' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyAllOfAllOf.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyNotNot.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, DataTypes200ResponseMyAllOfAllOf value) throws IOException { + public void write(JsonWriter out, DataTypes200ResponseMyNotNot value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public DataTypes200ResponseMyAllOfAllOf read(JsonReader in) throws IOException { + public DataTypes200ResponseMyNotNot read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -13118,18 +25268,18 @@ public class DataTypes200ResponseMyAllOfAllOf { } /** - * Create an instance of DataTypes200ResponseMyAllOfAllOf given an JSON string + * Create an instance of DataTypes200ResponseMyNotNot given an JSON string * * @param jsonString JSON string - * @return An instance of DataTypes200ResponseMyAllOfAllOf - * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAllOfAllOf + * @return An instance of DataTypes200ResponseMyNotNot + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyNotNot */ - public static DataTypes200ResponseMyAllOfAllOf fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAllOfAllOf.class); + public static DataTypes200ResponseMyNotNot fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyNotNot.class); } /** - * Convert an instance of DataTypes200ResponseMyAllOfAllOf to an JSON string + * Convert an instance of DataTypes200ResponseMyNotNot to an JSON string * * @return JSON string */ @@ -13139,7 +25289,7 @@ public class DataTypes200ResponseMyAllOfAllOf { } ", - "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAllOfAllOf1.java": "/* + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyObject.java": "/* * Data Types * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * @@ -13162,6 +25312,7 @@ import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import test.test.runtime.model.DataTypes200ResponseMyObjectOne; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -13185,37 +25336,63 @@ import java.util.Set; import test.test.runtime.JSON; /** - * DataTypes200ResponseMyAllOfAllOf1 + * DataTypes200ResponseMyObject */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DataTypes200ResponseMyAllOfAllOf1 { - public static final String SERIALIZED_NAME_SECOND = "second"; - @SerializedName(SERIALIZED_NAME_SECOND) - private String second; +public class DataTypes200ResponseMyObject { + public static final String SERIALIZED_NAME_ONE = "one"; + @SerializedName(SERIALIZED_NAME_ONE) + private DataTypes200ResponseMyObjectOne one; - public DataTypes200ResponseMyAllOfAllOf1() { + public static final String SERIALIZED_NAME_ONE_STRING = "oneString"; + @SerializedName(SERIALIZED_NAME_ONE_STRING) + private String oneString; + + public DataTypes200ResponseMyObject() { } - public DataTypes200ResponseMyAllOfAllOf1 second(String second) { + public DataTypes200ResponseMyObject one(DataTypes200ResponseMyObjectOne one) { - this.second = second; + this.one = one; return this; } /** - * Get second - * @return second + * Get one + * @return one **/ @javax.annotation.Nullable - public String getSecond() { - return second; + public DataTypes200ResponseMyObjectOne getOne() { + return one; } - public void setSecond(String second) { - this.second = second; + public void setOne(DataTypes200ResponseMyObjectOne one) { + this.one = one; + } + + + public DataTypes200ResponseMyObject oneString(String oneString) { + + this.oneString = oneString; + return this; + } + + /** + * Get oneString + * @return oneString + **/ + @javax.annotation.Nullable + + public String getOneString() { + return oneString; + } + + + public void setOneString(String oneString) { + this.oneString = oneString; } @@ -13228,20 +25405,22 @@ public class DataTypes200ResponseMyAllOfAllOf1 { if (o == null || getClass() != o.getClass()) { return false; } - DataTypes200ResponseMyAllOfAllOf1 dataTypes200ResponseMyAllOfAllOf1 = (DataTypes200ResponseMyAllOfAllOf1) o; - return Objects.equals(this.second, dataTypes200ResponseMyAllOfAllOf1.second); + DataTypes200ResponseMyObject dataTypes200ResponseMyObject = (DataTypes200ResponseMyObject) o; + return Objects.equals(this.one, dataTypes200ResponseMyObject.one) && + Objects.equals(this.oneString, dataTypes200ResponseMyObject.oneString); } @Override public int hashCode() { - return Objects.hash(second); + return Objects.hash(one, oneString); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class DataTypes200ResponseMyAllOfAllOf1 {\\n"); - sb.append(" second: ").append(toIndentedString(second)).append("\\n"); + sb.append("class DataTypes200ResponseMyObject {\\n"); + sb.append(" one: ").append(toIndentedString(one)).append("\\n"); + sb.append(" oneString: ").append(toIndentedString(oneString)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -13264,7 +25443,8 @@ public class DataTypes200ResponseMyAllOfAllOf1 { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("second"); + openapiFields.add("one"); + openapiFields.add("oneString"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); @@ -13274,24 +25454,28 @@ public class DataTypes200ResponseMyAllOfAllOf1 { * 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 DataTypes200ResponseMyAllOfAllOf1 + * @throws IOException if the JSON Object is invalid with respect to DataTypes200ResponseMyObject */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!DataTypes200ResponseMyAllOfAllOf1.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyAllOfAllOf1 is not found in the empty JSON string", DataTypes200ResponseMyAllOfAllOf1.openapiRequiredFields.toString())); + if (!DataTypes200ResponseMyObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyObject is not found in the empty JSON string", DataTypes200ResponseMyObject.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!DataTypes200ResponseMyAllOfAllOf1.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyAllOfAllOf1\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!DataTypes200ResponseMyObject.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyObject\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if ((jsonObj.get("second") != null && !jsonObj.get("second").isJsonNull()) && !jsonObj.get("second").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`second\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("second").toString())); + // validate the optional field \`one\` + if (jsonObj.get("one") != null && !jsonObj.get("one").isJsonNull()) { + DataTypes200ResponseMyObjectOne.validateJsonObject(jsonObj.getAsJsonObject("one")); + } + if ((jsonObj.get("oneString") != null && !jsonObj.get("oneString").isJsonNull()) && !jsonObj.get("oneString").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`oneString\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("oneString").toString())); } } @@ -13299,22 +25483,22 @@ public class DataTypes200ResponseMyAllOfAllOf1 { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!DataTypes200ResponseMyAllOfAllOf1.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DataTypes200ResponseMyAllOfAllOf1' and its subtypes + if (!DataTypes200ResponseMyObject.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyObject' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyAllOfAllOf1.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyObject.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, DataTypes200ResponseMyAllOfAllOf1 value) throws IOException { + public void write(JsonWriter out, DataTypes200ResponseMyObject value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public DataTypes200ResponseMyAllOfAllOf1 read(JsonReader in) throws IOException { + public DataTypes200ResponseMyObject read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -13325,18 +25509,18 @@ public class DataTypes200ResponseMyAllOfAllOf1 { } /** - * Create an instance of DataTypes200ResponseMyAllOfAllOf1 given an JSON string + * Create an instance of DataTypes200ResponseMyObject given an JSON string * * @param jsonString JSON string - * @return An instance of DataTypes200ResponseMyAllOfAllOf1 - * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAllOfAllOf1 + * @return An instance of DataTypes200ResponseMyObject + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyObject */ - public static DataTypes200ResponseMyAllOfAllOf1 fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAllOfAllOf1.class); + public static DataTypes200ResponseMyObject fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyObject.class); } /** - * Convert an instance of DataTypes200ResponseMyAllOfAllOf1 to an JSON string + * Convert an instance of DataTypes200ResponseMyObject to an JSON string * * @return JSON string */ @@ -13346,7 +25530,7 @@ public class DataTypes200ResponseMyAllOfAllOf1 { } ", - "src/main/java/test/test/runtime/model/DataTypes200ResponseMyAnyOf.java": "/* + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyObjectOne.java": "/* * Data Types * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * @@ -13363,249 +25547,221 @@ package test.test.runtime.model; import java.util.Objects; import java.util.Arrays; -import java.math.BigDecimal; - -import javax.ws.rs.core.GenericType; - -import java.io.IOException; -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 com.google.gson.Gson; -import com.google.gson.GsonBuilder; -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 java.io.IOException; +import test.test.runtime.model.DataTypes200ResponseMyObjectOneTwo; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; 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 com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; import test.test.runtime.JSON; +/** + * DataTypes200ResponseMyObjectOne + */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DataTypes200ResponseMyAnyOf extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(DataTypes200ResponseMyAnyOf.class.getName()); +public class DataTypes200ResponseMyObjectOne { + public static final String SERIALIZED_NAME_TWO_STRING = "twoString"; + @SerializedName(SERIALIZED_NAME_TWO_STRING) + private String twoString; - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DataTypes200ResponseMyAnyOf.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DataTypes200ResponseMyAnyOf' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter adapterBigDecimal = gson.getDelegateAdapter(this, TypeToken.get(BigDecimal.class)); - final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + public static final String SERIALIZED_NAME_TWO = "two"; + @SerializedName(SERIALIZED_NAME_TWO) + private DataTypes200ResponseMyObjectOneTwo two; - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DataTypes200ResponseMyAnyOf value) throws IOException { - if (value == null || value.getActualInstance() == null) { - elementAdapter.write(out, null); - return; - } + public DataTypes200ResponseMyObjectOne() { + } - // check if the actual instance is of the type \`BigDecimal\` - if (value.getActualInstance() instanceof BigDecimal) { - JsonObject obj = adapterBigDecimal.toJsonTree((BigDecimal)value.getActualInstance()).getAsJsonObject(); - elementAdapter.write(out, obj); - return; - } + public DataTypes200ResponseMyObjectOne twoString(String twoString) { + + this.twoString = twoString; + return this; + } + + /** + * Get twoString + * @return twoString + **/ + @javax.annotation.Nullable - // check if the actual instance is of the type \`String\` - if (value.getActualInstance() instanceof String) { - JsonObject obj = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonObject(); - elementAdapter.write(out, obj); - return; - } + public String getTwoString() { + return twoString; + } - throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: BigDecimal, String"); - } - @Override - public DataTypes200ResponseMyAnyOf read(JsonReader in) throws IOException { - Object deserialized = null; - JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + public void setTwoString(String twoString) { + this.twoString = twoString; + } - // deserialize BigDecimal - try { - // validate the JSON object to see if any exception is thrown - BigDecimal.validateJsonObject(jsonObject); - log.log(Level.FINER, "Input data matches schema 'BigDecimal'"); - DataTypes200ResponseMyAnyOf ret = new DataTypes200ResponseMyAnyOf(); - ret.setActualInstance(adapterBigDecimal.fromJsonTree(jsonObject)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'BigDecimal'", e); - } - // deserialize String - try { - // validate the JSON object to see if any exception is thrown - String.validateJsonObject(jsonObject); - log.log(Level.FINER, "Input data matches schema 'String'"); - DataTypes200ResponseMyAnyOf ret = new DataTypes200ResponseMyAnyOf(); - ret.setActualInstance(adapterString.fromJsonTree(jsonObject)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'String'", e); - } + public DataTypes200ResponseMyObjectOne two(DataTypes200ResponseMyObjectOneTwo two) { + + this.two = two; + return this; + } + /** + * Get two + * @return two + **/ + @javax.annotation.Nullable - throw new IOException(String.format("Failed deserialization for DataTypes200ResponseMyAnyOf: no class matched. JSON: %s", jsonObject.toString())); - } - }.nullSafe(); - } - } + public DataTypes200ResponseMyObjectOneTwo getTwo() { + return two; + } - // store a list of schema names defined in anyOf - public static final Map schemas = new HashMap(); - public DataTypes200ResponseMyAnyOf() { - super("anyOf", Boolean.FALSE); - } + public void setTwo(DataTypes200ResponseMyObjectOneTwo two) { + this.two = two; + } - public DataTypes200ResponseMyAnyOf(BigDecimal o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - public DataTypes200ResponseMyAnyOf(String o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - static { - schemas.put("BigDecimal", new GenericType() { - }); - schemas.put("String", new GenericType() { - }); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public Map getSchemas() { - return DataTypes200ResponseMyAnyOf.schemas; + if (o == null || getClass() != o.getClass()) { + return false; } + DataTypes200ResponseMyObjectOne dataTypes200ResponseMyObjectOne = (DataTypes200ResponseMyObjectOne) o; + return Objects.equals(this.twoString, dataTypes200ResponseMyObjectOne.twoString) && + Objects.equals(this.two, dataTypes200ResponseMyObjectOne.two); + } - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * BigDecimal, String - * - * It could be an instance of the 'anyOf' schemas. - * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). - */ - @Override - public void setActualInstance(Object instance) { - if (instance instanceof BigDecimal) { - super.setActualInstance(instance); - return; - } + @Override + public int hashCode() { + return Objects.hash(twoString, two); + } - if (instance instanceof String) { - super.setActualInstance(instance); - return; - } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DataTypes200ResponseMyObjectOne {\\n"); + sb.append(" twoString: ").append(toIndentedString(twoString)).append("\\n"); + sb.append(" two: ").append(toIndentedString(two)).append("\\n"); + sb.append("}"); + return sb.toString(); + } - throw new RuntimeException("Invalid instance type. Must be BigDecimal, String"); + /** + * 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 "); + } - /** - * Get the actual instance, which can be the following: - * BigDecimal, String - * - * @return The actual instance (BigDecimal, String) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - /** - * Get the actual instance of \`BigDecimal\`. If the actual instance is not \`BigDecimal\`, - * the ClassCastException will be thrown. - * - * @return The actual instance of \`BigDecimal\` - * @throws ClassCastException if the instance is not \`BigDecimal\` - */ - public BigDecimal getBigDecimal() throws ClassCastException { - return (BigDecimal)super.getActualInstance(); - } + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; - /** - * Get the actual instance of \`String\`. If the actual instance is not \`String\`, - * the ClassCastException will be thrown. - * - * @return The actual instance of \`String\` - * @throws ClassCastException if the instance is not \`String\` - */ - public String getString() throws ClassCastException { - return (String)super.getActualInstance(); - } + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("twoString"); + openapiFields.add("two"); + // 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 DataTypes200ResponseMyAnyOf + * @throws IOException if the JSON Object is invalid with respect to DataTypes200ResponseMyObjectOne */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { - // validate anyOf schemas one by one - int validCount = 0; - // validate the json string with BigDecimal - try { - BigDecimal.validateJsonObject(jsonObj); - return; // return earlier as at least one schema is valid with respect to the Json object - //validCount++; - } catch (Exception e) { - // continue to the next one - } - // validate the json string with String - try { - String.validateJsonObject(jsonObj); - return; // return earlier as at least one schema is valid with respect to the Json object - //validCount++; - } catch (Exception e) { - // continue to the next one - } - if (validCount == 0) { - throw new IOException(String.format("The JSON string is invalid for DataTypes200ResponseMyAnyOf with anyOf schemas: BigDecimal, String. JSON: %s", jsonObj.toString())); + if (jsonObj == null) { + if (!DataTypes200ResponseMyObjectOne.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyObjectOne is not found in the empty JSON string", DataTypes200ResponseMyObjectOne.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!DataTypes200ResponseMyObjectOne.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyObjectOne\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("twoString") != null && !jsonObj.get("twoString").isJsonNull()) && !jsonObj.get("twoString").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`twoString\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("twoString").toString())); + } + // validate the optional field \`two\` + if (jsonObj.get("two") != null && !jsonObj.get("two").isJsonNull()) { + DataTypes200ResponseMyObjectOneTwo.validateJsonObject(jsonObj.getAsJsonObject("two")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DataTypes200ResponseMyObjectOne.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyObjectOne' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyObjectOne.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DataTypes200ResponseMyObjectOne value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DataTypes200ResponseMyObjectOne read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); } } /** - * Create an instance of DataTypes200ResponseMyAnyOf given an JSON string + * Create an instance of DataTypes200ResponseMyObjectOne given an JSON string * * @param jsonString JSON string - * @return An instance of DataTypes200ResponseMyAnyOf - * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyAnyOf + * @return An instance of DataTypes200ResponseMyObjectOne + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyObjectOne */ - public static DataTypes200ResponseMyAnyOf fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyAnyOf.class); + public static DataTypes200ResponseMyObjectOne fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyObjectOne.class); } /** - * Convert an instance of DataTypes200ResponseMyAnyOf to an JSON string + * Convert an instance of DataTypes200ResponseMyObjectOne to an JSON string * * @return JSON string */ @@ -13615,7 +25771,7 @@ public class DataTypes200ResponseMyAnyOf extends AbstractOpenApiSchema { } ", - "src/main/java/test/test/runtime/model/DataTypes200ResponseMyNotNot.java": "/* + "src/main/java/test/test/runtime/model/DataTypes200ResponseMyObjectOneTwo.java": "/* * Data Types * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * @@ -13661,37 +25817,37 @@ import java.util.Set; import test.test.runtime.JSON; /** - * DataTypes200ResponseMyNotNot + * DataTypes200ResponseMyObjectOneTwo */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DataTypes200ResponseMyNotNot { - public static final String SERIALIZED_NAME_FOO = "foo"; - @SerializedName(SERIALIZED_NAME_FOO) - private String foo; +public class DataTypes200ResponseMyObjectOneTwo { + public static final String SERIALIZED_NAME_THREE_STRING = "threeString"; + @SerializedName(SERIALIZED_NAME_THREE_STRING) + private String threeString; - public DataTypes200ResponseMyNotNot() { + public DataTypes200ResponseMyObjectOneTwo() { } - public DataTypes200ResponseMyNotNot foo(String foo) { + public DataTypes200ResponseMyObjectOneTwo threeString(String threeString) { - this.foo = foo; + this.threeString = threeString; return this; } /** - * Get foo - * @return foo + * Get threeString + * @return threeString **/ @javax.annotation.Nullable - public String getFoo() { - return foo; + public String getThreeString() { + return threeString; } - public void setFoo(String foo) { - this.foo = foo; + public void setThreeString(String threeString) { + this.threeString = threeString; } @@ -13704,20 +25860,20 @@ public class DataTypes200ResponseMyNotNot { if (o == null || getClass() != o.getClass()) { return false; } - DataTypes200ResponseMyNotNot dataTypes200ResponseMyNotNot = (DataTypes200ResponseMyNotNot) o; - return Objects.equals(this.foo, dataTypes200ResponseMyNotNot.foo); + DataTypes200ResponseMyObjectOneTwo dataTypes200ResponseMyObjectOneTwo = (DataTypes200ResponseMyObjectOneTwo) o; + return Objects.equals(this.threeString, dataTypes200ResponseMyObjectOneTwo.threeString); } @Override public int hashCode() { - return Objects.hash(foo); + return Objects.hash(threeString); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class DataTypes200ResponseMyNotNot {\\n"); - sb.append(" foo: ").append(toIndentedString(foo)).append("\\n"); + sb.append("class DataTypes200ResponseMyObjectOneTwo {\\n"); + sb.append(" threeString: ").append(toIndentedString(threeString)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -13740,7 +25896,7 @@ public class DataTypes200ResponseMyNotNot { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("foo"); + openapiFields.add("threeString"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); @@ -13750,24 +25906,24 @@ public class DataTypes200ResponseMyNotNot { * 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 DataTypes200ResponseMyNotNot + * @throws IOException if the JSON Object is invalid with respect to DataTypes200ResponseMyObjectOneTwo */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!DataTypes200ResponseMyNotNot.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyNotNot is not found in the empty JSON string", DataTypes200ResponseMyNotNot.openapiRequiredFields.toString())); + if (!DataTypes200ResponseMyObjectOneTwo.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in DataTypes200ResponseMyObjectOneTwo is not found in the empty JSON string", DataTypes200ResponseMyObjectOneTwo.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!DataTypes200ResponseMyNotNot.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyNotNot\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!DataTypes200ResponseMyObjectOneTwo.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`DataTypes200ResponseMyObjectOneTwo\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - 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())); + if ((jsonObj.get("threeString") != null && !jsonObj.get("threeString").isJsonNull()) && !jsonObj.get("threeString").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`threeString\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("threeString").toString())); } } @@ -13775,22 +25931,22 @@ public class DataTypes200ResponseMyNotNot { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!DataTypes200ResponseMyNotNot.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DataTypes200ResponseMyNotNot' and its subtypes + if (!DataTypes200ResponseMyObjectOneTwo.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DataTypes200ResponseMyObjectOneTwo' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyNotNot.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DataTypes200ResponseMyObjectOneTwo.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, DataTypes200ResponseMyNotNot value) throws IOException { + public void write(JsonWriter out, DataTypes200ResponseMyObjectOneTwo value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public DataTypes200ResponseMyNotNot read(JsonReader in) throws IOException { + public DataTypes200ResponseMyObjectOneTwo read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -13801,18 +25957,18 @@ public class DataTypes200ResponseMyNotNot { } /** - * Create an instance of DataTypes200ResponseMyNotNot given an JSON string + * Create an instance of DataTypes200ResponseMyObjectOneTwo given an JSON string * * @param jsonString JSON string - * @return An instance of DataTypes200ResponseMyNotNot - * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyNotNot + * @return An instance of DataTypes200ResponseMyObjectOneTwo + * @throws IOException if the JSON string is invalid with respect to DataTypes200ResponseMyObjectOneTwo */ - public static DataTypes200ResponseMyNotNot fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyNotNot.class); + public static DataTypes200ResponseMyObjectOneTwo fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DataTypes200ResponseMyObjectOneTwo.class); } /** - * Convert an instance of DataTypes200ResponseMyNotNot to an JSON string + * Convert an instance of DataTypes200ResponseMyObjectOneTwo to an JSON string * * @return JSON string */ 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 d288a6f15..070d268a6 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 @@ -3458,6 +3458,6085 @@ class RESTClientObject: } `; +exports[`Python Client Code Generation Script Unit Tests Generates With composite-models.yaml 1`] = ` +{ + ".gitattributes": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". + +/.gitattributes linguist-generated +/.github/workflows/pull-request-lint.yml linguist-generated +/.gitignore linguist-generated +/.openapi-generator-ignore linguist-generated +/.pdk/dynamic-files/openapitools.json linguist-generated +/.projen/** linguist-generated +/.projen/deps.json linguist-generated +/.projen/files.json linguist-generated +/.projen/tasks.json linguist-generated +/pyproject.toml linguist-generated", + ".gitignore": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". +node_modules/ +!/.gitattributes +!/.projen/tasks.json +!/.projen/deps.json +!/.projen/files.json +!/.github/workflows/pull-request-lint.yml +!/pyproject.toml +/poetry.toml +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST +*.manifest +*.spec +pip-log.txt +pip-delete-this-directory.txt +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ +*.mo +*.pot +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal +instance/ +.webassets-cache +.scrapy +docs/_build/ +.pybuilder/ +target/ +.ipynb_checkpoints +profile_default/ +ipython_config.py +__pypackages__/ +celerybeat-schedule +celerybeat.pid +*.sage.py +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +.spyderproject +.spyproject +.ropeproject +/site +.mypy_cache/ +.dmypy.json +dmypy.json +.pyre/ +.pytype/ +cython_debug/ +!/.openapi-generator-ignore +!/.pdk/dynamic-files/openapitools.json +/openapitools.json +test_project +docs +README.md +.openapi-generator +!/.projenrc.py +", + ".openapi-generator-ignore": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". +.gitignore +test +test/* +test/**/* +.github +.github/* +.github/**/* +.gitlab-ci.yml +.travis.yml +git_push.sh +tox.ini +requirements.txt +test-requirements.txt +setup.py +setup.cfg +pyproject.toml +", + ".openapi-generator/FILES": "README.md +docs/A.md +docs/AllOfInlineAndRefs.md +docs/AllOfRefs.md +docs/AnyOfInlineAndRefs.md +docs/AnyOfInlineAndRefsAnyOf.md +docs/AnyOfInlineAndRefsAnyOf1.md +docs/AnyOfPrimitives.md +docs/AnyOfPrimitivesAndRefs.md +docs/AnyOfRefs.md +docs/B.md +docs/C.md +docs/DefaultApi.md +docs/OneOfInlineAndRefs.md +docs/OneOfPrimitives.md +docs/OneOfPrimitivesAndRefs.md +docs/OneOfRefs.md +docs/Wrapper.md +docs/WrapperAllOf.md +docs/WrapperAnyOf.md +docs/WrapperOneOf.md +test_project/__init__.py +test_project/__interceptors.py +test_project/api/__init__.py +test_project/api/default_api.py +test_project/api/operation_config.py +test_project/api_client.py +test_project/api_response.py +test_project/configuration.py +test_project/exceptions.py +test_project/models/__init__.py +test_project/models/a.py +test_project/models/all_of_inline_and_refs.py +test_project/models/all_of_refs.py +test_project/models/any_of_inline_and_refs.py +test_project/models/any_of_inline_and_refs_any_of.py +test_project/models/any_of_inline_and_refs_any_of1.py +test_project/models/any_of_primitives.py +test_project/models/any_of_primitives_and_refs.py +test_project/models/any_of_refs.py +test_project/models/b.py +test_project/models/c.py +test_project/models/one_of_inline_and_refs.py +test_project/models/one_of_primitives.py +test_project/models/one_of_primitives_and_refs.py +test_project/models/one_of_refs.py +test_project/models/wrapper.py +test_project/models/wrapper_all_of.py +test_project/models/wrapper_any_of.py +test_project/models/wrapper_one_of.py +test_project/py.typed +test_project/response.py +test_project/rest.py +test_project/interceptors/try_catch.py +test_project/interceptors/response_headers.py +test_project/interceptors/powertools/logger.py +test_project/interceptors/powertools/tracer.py +test_project/interceptors/powertools/metrics.py +test_project/interceptors/__init__.py", + ".openapi-generator/VERSION": "7.1.0", + ".pdk/dynamic-files/openapitools.json": { + "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "//": "~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen".", + "generator-cli": { + "storageDir": "~/.open-api-generator-cli", + "version": "7.1.0", + }, + "spaces": 2, + }, + ".projen/deps.json": { + "//": "~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen".", + "dependencies": [ + { + "name": "projen", + "type": "devenv", + "version": "99.99.99", + }, + { + "name": "aenum", + "type": "runtime", + "version": "^3.1.11", + }, + { + "name": "aws-lambda-powertools", + "type": "runtime", + "version": "{extras=["tracer", "aws-sdk"],version="^2.28.0"}", + }, + { + "name": "pydantic", + "type": "runtime", + "version": "^2.5.2", + }, + { + "name": "python-dateutil", + "type": "runtime", + "version": "~2.8.2", + }, + { + "name": "python", + "type": "runtime", + "version": "^3.9", + }, + { + "name": "urllib3", + "type": "runtime", + "version": "~1.26.7", + }, + ], + }, + ".projen/files.json": { + "//": "~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen".", + "files": [ + ".gitattributes", + ".github/workflows/pull-request-lint.yml", + ".gitignore", + ".openapi-generator-ignore", + ".pdk/dynamic-files/openapitools.json", + ".projen/deps.json", + ".projen/files.json", + ".projen/tasks.json", + "poetry.toml", + "pyproject.toml", + ], + }, + ".projen/tasks.json": { + "//": "~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen".", + "env": { + "AWS_PDK_VERSION": "0.0.0", + "PATH": "$(echo $(poetry env info -p)/bin:$PATH)", + "VIRTUAL_ENV": "$(poetry env info -p || poetry run poetry env info -p)", + }, + "tasks": { + "build": { + "description": "Full release build", + "name": "build", + "steps": [ + { + "spawn": "default", + }, + { + "spawn": "pre-compile", + }, + { + "spawn": "compile", + }, + { + "spawn": "post-compile", + }, + { + "spawn": "test", + }, + { + "spawn": "package", + }, + ], + }, + "clobber": { + "condition": "git diff --exit-code > /dev/null", + "description": "hard resets to HEAD of origin and cleans the local repo", + "env": { + "BRANCH": "$(git branch --show-current)", + }, + "name": "clobber", + "steps": [ + { + "exec": "git checkout -b scratch", + "name": "save current HEAD in "scratch" branch", + }, + { + "exec": "git checkout $BRANCH", + }, + { + "exec": "git fetch origin", + "name": "fetch latest changes from origin", + }, + { + "exec": "git reset --hard origin/$BRANCH", + "name": "hard reset to origin commit", + }, + { + "exec": "git clean -fdx", + "name": "clean all untracked files", + }, + { + "say": "ready to rock! (unpushed commits are under the "scratch" branch)", + }, + ], + }, + "compile": { + "description": "Only compile", + "name": "compile", + }, + "create-openapitools.json": { + "name": "create-openapitools.json", + "steps": [ + { + "exec": "cp -f .pdk/dynamic-files/openapitools.json openapitools.json", + }, + ], + }, + "default": { + "description": "Synthesize project files", + "name": "default", + "steps": [ + { + "exec": "python .projenrc.py", + }, + ], + }, + "eject": { + "description": "Remove projen from the project", + "env": { + "PROJEN_EJECTING": "true", + }, + "name": "eject", + "steps": [ + { + "spawn": "default", + }, + ], + }, + "generate": { + "name": "generate", + "steps": [ + { + "spawn": "create-openapitools.json", + }, + { + "exec": "npx --yes -p @aws/pdk@$AWS_PDK_VERSION type-safe-api.clean-openapi-generated-code --code-path .", + }, + { + "exec": "npx --yes -p @aws/pdk@$AWS_PDK_VERSION type-safe-api.generate --generator python --spec-path spec.yaml --output-path . --generator-dir python --src-dir test_project --tst-dir test --additional-properties "packageName=test_project,projectName=test_project" --openapi-normalizer "KEEP_ONLY_FIRST_TAG_IN_OPERATION=true" --generate-alias-as-model", + }, + ], + }, + "install": { + "description": "Install dependencies and update lockfile", + "name": "install", + "steps": [ + { + "exec": "mkdir -p test_project && touch test_project/__init__.py README.md", + }, + { + "exec": "poetry update", + }, + ], + }, + "install:ci": { + "description": "Install dependencies with frozen lockfile", + "name": "install:ci", + "steps": [ + { + "exec": "mkdir -p test_project && touch test_project/__init__.py README.md", + }, + { + "exec": "poetry check --lock && poetry install", + }, + ], + }, + "package": { + "description": "Creates the distribution package", + "name": "package", + "steps": [ + { + "exec": "poetry build", + }, + ], + }, + "post-compile": { + "description": "Runs after successful compilation", + "name": "post-compile", + }, + "pre-compile": { + "description": "Prepare the project for compilation", + "name": "pre-compile", + "steps": [ + { + "spawn": "generate", + }, + ], + }, + "publish": { + "description": "Uploads the package to PyPI.", + "name": "publish", + "steps": [ + { + "exec": "poetry publish", + }, + ], + }, + "publish:test": { + "description": "Uploads the package against a test PyPI endpoint.", + "name": "publish:test", + "steps": [ + { + "exec": "poetry publish -r testpypi", + }, + ], + }, + "test": { + "description": "Run tests", + "name": "test", + }, + }, + }, + "README.md": "# test_project +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonClientCodegen + +## Requirements. + +Python 3.7+ + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +\`\`\`sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +\`\`\` +(you may need to run \`pip\` with root permission: \`sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git\`) + +Then import the package: +\`\`\`python +import test_project +\`\`\` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +\`\`\`sh +python setup.py install --user +\`\`\` +(or \`sudo python setup.py install\` to install the package for all users) + +Then import the package: +\`\`\`python +import test_project +\`\`\` + +### Tests + +Execute \`pytest\` to run the tests. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +\`\`\`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.op_get() + print("The response of DefaultApi->op_get:\\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->op_get: %s\\n" % e) + +\`\`\` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**op_get**](docs/DefaultApi.md#op_get) | **GET** /op | + + +## Documentation For Models + + - [A](docs/A.md) + - [AllOfInlineAndRefs](docs/AllOfInlineAndRefs.md) + - [AllOfRefs](docs/AllOfRefs.md) + - [AnyOfInlineAndRefs](docs/AnyOfInlineAndRefs.md) + - [AnyOfInlineAndRefsAnyOf](docs/AnyOfInlineAndRefsAnyOf.md) + - [AnyOfInlineAndRefsAnyOf1](docs/AnyOfInlineAndRefsAnyOf1.md) + - [AnyOfPrimitives](docs/AnyOfPrimitives.md) + - [AnyOfPrimitivesAndRefs](docs/AnyOfPrimitivesAndRefs.md) + - [AnyOfRefs](docs/AnyOfRefs.md) + - [B](docs/B.md) + - [C](docs/C.md) + - [OneOfInlineAndRefs](docs/OneOfInlineAndRefs.md) + - [OneOfPrimitives](docs/OneOfPrimitives.md) + - [OneOfPrimitivesAndRefs](docs/OneOfPrimitivesAndRefs.md) + - [OneOfRefs](docs/OneOfRefs.md) + - [Wrapper](docs/Wrapper.md) + - [WrapperAllOf](docs/WrapperAllOf.md) + - [WrapperAnyOf](docs/WrapperAnyOf.md) + - [WrapperOneOf](docs/WrapperOneOf.md) + + + +## Documentation For Authorization + +Endpoints do not require authorization. + + +## Author + + + + +", + "docs/A.md": "# A + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | + +## Example + +\`\`\`python +from test_project.models.a import A + +# TODO update the JSON string below +json = "{}" +# create an instance of A from a JSON string +a_instance = A.from_json(json) +# print the JSON string representation of the object +print A.to_json() + +# convert the object into a dict +a_dict = a_instance.to_dict() +# create an instance of A from a dict +a_form_dict = a.from_dict(a_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/AllOfInlineAndRefs.md": "# AllOfInlineAndRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | +**b** | **str** | | +**c** | **str** | | +**d** | **str** | | +**e** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.all_of_inline_and_refs import AllOfInlineAndRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of AllOfInlineAndRefs from a JSON string +all_of_inline_and_refs_instance = AllOfInlineAndRefs.from_json(json) +# print the JSON string representation of the object +print AllOfInlineAndRefs.to_json() + +# convert the object into a dict +all_of_inline_and_refs_dict = all_of_inline_and_refs_instance.to_dict() +# create an instance of AllOfInlineAndRefs from a dict +all_of_inline_and_refs_form_dict = all_of_inline_and_refs.from_dict(all_of_inline_and_refs_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/AllOfRefs.md": "# AllOfRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | +**b** | **str** | | +**c** | **str** | | + +## Example + +\`\`\`python +from test_project.models.all_of_refs import AllOfRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of AllOfRefs from a JSON string +all_of_refs_instance = AllOfRefs.from_json(json) +# print the JSON string representation of the object +print AllOfRefs.to_json() + +# convert the object into a dict +all_of_refs_dict = all_of_refs_instance.to_dict() +# create an instance of AllOfRefs from a dict +all_of_refs_form_dict = all_of_refs.from_dict(all_of_refs_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/AnyOfInlineAndRefs.md": "# AnyOfInlineAndRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**d** | **str** | | +**a** | **str** | | +**b** | **str** | | +**c** | **str** | | +**e** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.any_of_inline_and_refs import AnyOfInlineAndRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfInlineAndRefs from a JSON string +any_of_inline_and_refs_instance = AnyOfInlineAndRefs.from_json(json) +# print the JSON string representation of the object +print AnyOfInlineAndRefs.to_json() + +# convert the object into a dict +any_of_inline_and_refs_dict = any_of_inline_and_refs_instance.to_dict() +# create an instance of AnyOfInlineAndRefs from a dict +any_of_inline_and_refs_form_dict = any_of_inline_and_refs.from_dict(any_of_inline_and_refs_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/AnyOfInlineAndRefsAnyOf.md": "# AnyOfInlineAndRefsAnyOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**d** | **str** | | + +## Example + +\`\`\`python +from test_project.models.any_of_inline_and_refs_any_of import AnyOfInlineAndRefsAnyOf + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfInlineAndRefsAnyOf from a JSON string +any_of_inline_and_refs_any_of_instance = AnyOfInlineAndRefsAnyOf.from_json(json) +# print the JSON string representation of the object +print AnyOfInlineAndRefsAnyOf.to_json() + +# convert the object into a dict +any_of_inline_and_refs_any_of_dict = any_of_inline_and_refs_any_of_instance.to_dict() +# create an instance of AnyOfInlineAndRefsAnyOf from a dict +any_of_inline_and_refs_any_of_form_dict = any_of_inline_and_refs_any_of.from_dict(any_of_inline_and_refs_any_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/AnyOfInlineAndRefsAnyOf1.md": "# AnyOfInlineAndRefsAnyOf1 + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**e** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.any_of_inline_and_refs_any_of1 import AnyOfInlineAndRefsAnyOf1 + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfInlineAndRefsAnyOf1 from a JSON string +any_of_inline_and_refs_any_of1_instance = AnyOfInlineAndRefsAnyOf1.from_json(json) +# print the JSON string representation of the object +print AnyOfInlineAndRefsAnyOf1.to_json() + +# convert the object into a dict +any_of_inline_and_refs_any_of1_dict = any_of_inline_and_refs_any_of1_instance.to_dict() +# create an instance of AnyOfInlineAndRefsAnyOf1 from a dict +any_of_inline_and_refs_any_of1_form_dict = any_of_inline_and_refs_any_of1.from_dict(any_of_inline_and_refs_any_of1_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/AnyOfPrimitives.md": "# AnyOfPrimitives + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +\`\`\`python +from test_project.models.any_of_primitives import AnyOfPrimitives + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfPrimitives from a JSON string +any_of_primitives_instance = AnyOfPrimitives.from_json(json) +# print the JSON string representation of the object +print AnyOfPrimitives.to_json() + +# convert the object into a dict +any_of_primitives_dict = any_of_primitives_instance.to_dict() +# create an instance of AnyOfPrimitives from a dict +any_of_primitives_form_dict = any_of_primitives.from_dict(any_of_primitives_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/AnyOfPrimitivesAndRefs.md": "# AnyOfPrimitivesAndRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | + +## Example + +\`\`\`python +from test_project.models.any_of_primitives_and_refs import AnyOfPrimitivesAndRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfPrimitivesAndRefs from a JSON string +any_of_primitives_and_refs_instance = AnyOfPrimitivesAndRefs.from_json(json) +# print the JSON string representation of the object +print AnyOfPrimitivesAndRefs.to_json() + +# convert the object into a dict +any_of_primitives_and_refs_dict = any_of_primitives_and_refs_instance.to_dict() +# create an instance of AnyOfPrimitivesAndRefs from a dict +any_of_primitives_and_refs_form_dict = any_of_primitives_and_refs.from_dict(any_of_primitives_and_refs_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/AnyOfRefs.md": "# AnyOfRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | +**b** | **str** | | +**c** | **str** | | + +## Example + +\`\`\`python +from test_project.models.any_of_refs import AnyOfRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfRefs from a JSON string +any_of_refs_instance = AnyOfRefs.from_json(json) +# print the JSON string representation of the object +print AnyOfRefs.to_json() + +# convert the object into a dict +any_of_refs_dict = any_of_refs_instance.to_dict() +# create an instance of AnyOfRefs from a dict +any_of_refs_form_dict = any_of_refs.from_dict(any_of_refs_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/B.md": "# B + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**b** | **str** | | + +## Example + +\`\`\`python +from test_project.models.b import B + +# TODO update the JSON string below +json = "{}" +# create an instance of B from a JSON string +b_instance = B.from_json(json) +# print the JSON string representation of the object +print B.to_json() + +# convert the object into a dict +b_dict = b_instance.to_dict() +# create an instance of B from a dict +b_form_dict = b.from_dict(b_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/C.md": "# C + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**c** | **str** | | + +## Example + +\`\`\`python +from test_project.models.c import C + +# TODO update the JSON string below +json = "{}" +# create an instance of C from a JSON string +c_instance = C.from_json(json) +# print the JSON string representation of the object +print C.to_json() + +# convert the object into a dict +c_dict = c_instance.to_dict() +# create an instance of C from a dict +c_form_dict = c.from_dict(c_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 + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**op_get**](DefaultApi.md#op_get) | **GET** /op | + + +# **op_get** +> Wrapper op_get() + + + +### Example + +\`\`\`python +import time +import os +import test_project +from test_project.models.wrapper import Wrapper +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.op_get() + print("The response of DefaultApi->op_get:\\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->op_get: %s\\n" % e) +\`\`\` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Wrapper**](Wrapper.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful response | - | + +[[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/OneOfInlineAndRefs.md": "# OneOfInlineAndRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**d** | **str** | | +**a** | **str** | | +**b** | **str** | | +**c** | **str** | | +**e** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.one_of_inline_and_refs import OneOfInlineAndRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfInlineAndRefs from a JSON string +one_of_inline_and_refs_instance = OneOfInlineAndRefs.from_json(json) +# print the JSON string representation of the object +print OneOfInlineAndRefs.to_json() + +# convert the object into a dict +one_of_inline_and_refs_dict = one_of_inline_and_refs_instance.to_dict() +# create an instance of OneOfInlineAndRefs from a dict +one_of_inline_and_refs_form_dict = one_of_inline_and_refs.from_dict(one_of_inline_and_refs_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/OneOfPrimitives.md": "# OneOfPrimitives + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +\`\`\`python +from test_project.models.one_of_primitives import OneOfPrimitives + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfPrimitives from a JSON string +one_of_primitives_instance = OneOfPrimitives.from_json(json) +# print the JSON string representation of the object +print OneOfPrimitives.to_json() + +# convert the object into a dict +one_of_primitives_dict = one_of_primitives_instance.to_dict() +# create an instance of OneOfPrimitives from a dict +one_of_primitives_form_dict = one_of_primitives.from_dict(one_of_primitives_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/OneOfPrimitivesAndRefs.md": "# OneOfPrimitivesAndRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | + +## Example + +\`\`\`python +from test_project.models.one_of_primitives_and_refs import OneOfPrimitivesAndRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfPrimitivesAndRefs from a JSON string +one_of_primitives_and_refs_instance = OneOfPrimitivesAndRefs.from_json(json) +# print the JSON string representation of the object +print OneOfPrimitivesAndRefs.to_json() + +# convert the object into a dict +one_of_primitives_and_refs_dict = one_of_primitives_and_refs_instance.to_dict() +# create an instance of OneOfPrimitivesAndRefs from a dict +one_of_primitives_and_refs_form_dict = one_of_primitives_and_refs.from_dict(one_of_primitives_and_refs_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/OneOfRefs.md": "# OneOfRefs + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | +**b** | **str** | | +**c** | **str** | | + +## Example + +\`\`\`python +from test_project.models.one_of_refs import OneOfRefs + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfRefs from a JSON string +one_of_refs_instance = OneOfRefs.from_json(json) +# print the JSON string representation of the object +print OneOfRefs.to_json() + +# convert the object into a dict +one_of_refs_dict = one_of_refs_instance.to_dict() +# create an instance of OneOfRefs from a dict +one_of_refs_form_dict = one_of_refs.from_dict(one_of_refs_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/Wrapper.md": "# Wrapper + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**all_of** | [**WrapperAllOf**](WrapperAllOf.md) | | [optional] +**any_of** | [**WrapperAnyOf**](WrapperAnyOf.md) | | [optional] +**one_of** | [**WrapperOneOf**](WrapperOneOf.md) | | [optional] + +## Example + +\`\`\`python +from test_project.models.wrapper import Wrapper + +# TODO update the JSON string below +json = "{}" +# create an instance of Wrapper from a JSON string +wrapper_instance = Wrapper.from_json(json) +# print the JSON string representation of the object +print Wrapper.to_json() + +# convert the object into a dict +wrapper_dict = wrapper_instance.to_dict() +# create an instance of Wrapper from a dict +wrapper_form_dict = wrapper.from_dict(wrapper_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/WrapperAllOf.md": "# WrapperAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**refs** | [**AllOfRefs**](AllOfRefs.md) | | [optional] +**inline_and_refs** | [**AllOfInlineAndRefs**](AllOfInlineAndRefs.md) | | [optional] + +## Example + +\`\`\`python +from test_project.models.wrapper_all_of import WrapperAllOf + +# TODO update the JSON string below +json = "{}" +# create an instance of WrapperAllOf from a JSON string +wrapper_all_of_instance = WrapperAllOf.from_json(json) +# print the JSON string representation of the object +print WrapperAllOf.to_json() + +# convert the object into a dict +wrapper_all_of_dict = wrapper_all_of_instance.to_dict() +# create an instance of WrapperAllOf from a dict +wrapper_all_of_form_dict = wrapper_all_of.from_dict(wrapper_all_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/WrapperAnyOf.md": "# WrapperAnyOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**refs** | [**AnyOfRefs**](AnyOfRefs.md) | | [optional] +**inline_and_refs** | [**AnyOfInlineAndRefs**](AnyOfInlineAndRefs.md) | | [optional] +**primitives** | [**AnyOfPrimitives**](AnyOfPrimitives.md) | | [optional] +**primitives_and_refs** | [**AnyOfPrimitivesAndRefs**](AnyOfPrimitivesAndRefs.md) | | [optional] + +## Example + +\`\`\`python +from test_project.models.wrapper_any_of import WrapperAnyOf + +# TODO update the JSON string below +json = "{}" +# create an instance of WrapperAnyOf from a JSON string +wrapper_any_of_instance = WrapperAnyOf.from_json(json) +# print the JSON string representation of the object +print WrapperAnyOf.to_json() + +# convert the object into a dict +wrapper_any_of_dict = wrapper_any_of_instance.to_dict() +# create an instance of WrapperAnyOf from a dict +wrapper_any_of_form_dict = wrapper_any_of.from_dict(wrapper_any_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/WrapperOneOf.md": "# WrapperOneOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**refs** | [**OneOfRefs**](OneOfRefs.md) | | [optional] +**inline_and_refs** | [**OneOfInlineAndRefs**](OneOfInlineAndRefs.md) | | [optional] +**primitives** | [**OneOfPrimitives**](OneOfPrimitives.md) | | [optional] +**primitives_and_refs** | [**OneOfPrimitivesAndRefs**](OneOfPrimitivesAndRefs.md) | | [optional] + +## Example + +\`\`\`python +from test_project.models.wrapper_one_of import WrapperOneOf + +# TODO update the JSON string below +json = "{}" +# create an instance of WrapperOneOf from a JSON string +wrapper_one_of_instance = WrapperOneOf.from_json(json) +# print the JSON string representation of the object +print WrapperOneOf.to_json() + +# convert the object into a dict +wrapper_one_of_dict = wrapper_one_of_instance.to_dict() +# create an instance of WrapperOneOf from a dict +wrapper_one_of_form_dict = wrapper_one_of.from_dict(wrapper_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) + + +", + "openapitools.json": { + "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "//": "~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen".", + "generator-cli": { + "storageDir": "~/.open-api-generator-cli", + "version": "7.1.0", + }, + "spaces": 2, + }, + "poetry.toml": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". + +[repositories.testpypi] +url = "https://test.pypi.org/legacy/" +", + "test_project/__init__.py": "# coding: utf-8 + +# flake8: noqa + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from test_project.api.default_api import DefaultApi + +# import ApiClient +from test_project.api_response import ApiResponse +from test_project.api_client import ApiClient +from test_project.configuration import Configuration +from test_project.exceptions import OpenApiException +from test_project.exceptions import ApiTypeError +from test_project.exceptions import ApiValueError +from test_project.exceptions import ApiKeyError +from test_project.exceptions import ApiAttributeError +from test_project.exceptions import ApiException + +# import models into sdk package +from test_project.models.a import A +from test_project.models.all_of_inline_and_refs import AllOfInlineAndRefs +from test_project.models.all_of_refs import AllOfRefs +from test_project.models.any_of_inline_and_refs import AnyOfInlineAndRefs +from test_project.models.any_of_inline_and_refs_any_of import AnyOfInlineAndRefsAnyOf +from test_project.models.any_of_inline_and_refs_any_of1 import AnyOfInlineAndRefsAnyOf1 +from test_project.models.any_of_primitives import AnyOfPrimitives +from test_project.models.any_of_primitives_and_refs import AnyOfPrimitivesAndRefs +from test_project.models.any_of_refs import AnyOfRefs +from test_project.models.b import B +from test_project.models.c import C +from test_project.models.one_of_inline_and_refs import OneOfInlineAndRefs +from test_project.models.one_of_primitives import OneOfPrimitives +from test_project.models.one_of_primitives_and_refs import OneOfPrimitivesAndRefs +from test_project.models.one_of_refs import OneOfRefs +from test_project.models.wrapper import Wrapper +from test_project.models.wrapper_all_of import WrapperAllOf +from test_project.models.wrapper_any_of import WrapperAnyOf +from test_project.models.wrapper_one_of import WrapperOneOf +", + "test_project/api/__init__.py": "# flake8: noqa + +# import apis into api package +from test_project.api.default_api import DefaultApi + +", + "test_project/api/default_api.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings + +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any + +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated + +from test_project.models.wrapper import Wrapper + +from test_project.api_client import ApiClient +from test_project.api_response import ApiResponse +from test_project.rest import RESTResponseType + + +class DefaultApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def op_get( + 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, + ) -> Wrapper: + """op_get + + + :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._op_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wrapper" + + } + 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 op_get_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[Wrapper]: + """op_get + + + :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._op_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wrapper" + + } + 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 op_get_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: + """op_get + + + :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._op_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wrapper" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _op_get_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='GET', + resource_path='/op', + 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]): + op_get: T + ... + +# Look up path and http method for a given operation name +OperationLookup = { + "op_get": { + "path": "/op", + "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}'") + +def coerce_parameter(base_name, data_type, raw_string_parameters, raw_string_array_parameters, required): + if data_type == "float": + assert_required(required, base_name, raw_string_parameters) + param = raw_string_parameters.get(base_name) + return None if param is None else coerce_float(base_name, param) + elif data_type == "int": + assert_required(required, base_name, raw_string_parameters) + param = raw_string_parameters.get(base_name) + return None if param is None else coerce_int(base_name, param) + elif data_type == "bool": + assert_required(required, base_name, raw_string_parameters) + param = raw_string_parameters.get(base_name) + return None if param is None else coerce_bool(base_name, param) + elif data_type == "datetime": + assert_required(required, base_name, raw_string_parameters) + param = raw_string_parameters.get(base_name) + return None if param is None else coerce_datetime(base_name, param) + elif data_type == "List[float]": + assert_required(required, base_name, raw_string_array_parameters) + param = raw_string_array_parameters.get(base_name) + return None if param is None else [coerce_float(base_name, p) for p in param] + elif data_type == "List[int]": + assert_required(required, base_name, raw_string_array_parameters) + param = raw_string_array_parameters.get(base_name) + return None if param is None else [coerce_int(base_name, p) for p in param] + elif data_type == "List[bool]": + assert_required(required, base_name, raw_string_array_parameters) + param = raw_string_array_parameters.get(base_name) + return None if param is None else [coerce_bool(base_name, p) for p in param] + elif data_type == "List[datetime]": + assert_required(required, base_name, raw_string_array_parameters) + param = raw_string_array_parameters.get(base_name) + return None if param is None else [coerce_datetime(base_name, p) for p in param] + elif data_type == "List[str]": + assert_required(required, base_name, raw_string_array_parameters) + return raw_string_array_parameters.get(base_name) + else: # data_type == "str" + assert_required(required, base_name, raw_string_parameters) + return raw_string_parameters.get(base_name) + + +def extract_response_headers_from_interceptors(interceptors): + headers = {} + for interceptor in interceptors: + additional_headers = getattr(interceptor, "__type_safe_api_response_headers", None) + headers = {**headers, **(additional_headers or {})} + return headers + + +RequestParameters = TypeVar('RequestParameters') +RequestBody = TypeVar('RequestBody') +ResponseBody = TypeVar('ResponseBody') +StatusCode = TypeVar('StatusCode') + +@dataclass +class ApiRequest(Generic[RequestParameters, RequestBody]): + request_parameters: RequestParameters + body: RequestBody + event: Any + context: Any + interceptor_context: Dict[str, Any] + +@dataclass +class ChainedApiRequest(ApiRequest[RequestParameters, RequestBody], + Generic[RequestParameters, RequestBody]): + + chain: 'HandlerChain' + +@dataclass +class ApiResponse(Exception, Generic[StatusCode, ResponseBody]): + status_code: StatusCode + headers: Dict[str, str] + body: ResponseBody + multi_value_headers: Optional[Dict[str, List[str]]] = None + +class HandlerChain(Generic[RequestParameters, RequestBody, StatusCode, ResponseBody]): + def next(self, request: ChainedApiRequest[RequestParameters, RequestBody]) -> ApiResponse[StatusCode, ResponseBody]: + raise Exception("Not implemented!") + +def _build_handler_chain(_interceptors, handler) -> HandlerChain: + if len(_interceptors) == 0: + class BaseHandlerChain(HandlerChain[RequestParameters, RequestBody, StatusCode, ResponseBody]): + def next(self, request: ApiRequest[RequestParameters, RequestBody]) -> ApiResponse[StatusCode, ResponseBody]: + return handler(request) + return BaseHandlerChain() + else: + interceptor = _interceptors[0] + + class RemainingHandlerChain(HandlerChain[RequestParameters, RequestBody, StatusCode, ResponseBody]): + def next(self, request: ChainedApiRequest[RequestParameters, RequestBody]) -> ApiResponse[StatusCode, ResponseBody]: + return interceptor(ChainedApiRequest( + request_parameters = request.request_parameters, + body = request.body, + event = request.event, + context = request.context, + interceptor_context = request.interceptor_context, + chain = _build_handler_chain(_interceptors[1:len(_interceptors)], handler), + )) + return RemainingHandlerChain() + + +class OpGetRequestParameters(BaseModel): + """ + Query, path and header parameters for the OpGet 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) -> OpGetRequestParameters: + 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) -> OpGetRequestParameters: + if obj is None: + return None + return OpGetRequestParameters.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) +OpGetRequestBody = Any + +OpGet200OperationResponse = ApiResponse[Literal[200], Wrapper] +OpGetOperationResponses = Union[OpGet200OperationResponse, ] + +# Request type for op_get +OpGetRequest = ApiRequest[OpGetRequestParameters, OpGetRequestBody] +OpGetChainedRequest = ChainedApiRequest[OpGetRequestParameters, OpGetRequestBody] + +class OpGetHandlerFunction(Protocol): + def __call__(self, input: OpGetRequest, **kwargs) -> OpGetOperationResponses: + ... + +OpGetInterceptor = Callable[[OpGetChainedRequest], OpGetOperationResponses] + +def op_get_handler(_handler: OpGetHandlerFunction = None, interceptors: List[OpGetInterceptor] = []): + """ + Decorator for an api handler for the op_get operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: OpGetHandlerFunction): + @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 = OpGetRequestParameters.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": "op_get", + } + + 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 op_get_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: + op_get: 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 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + 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)) + + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # 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 + + # 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 + + return method, url, header_params, body, post_params + + + 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 + """ + + 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 + ) + + except ApiException as e: + if e.body: + e.body = e.body.decode('utf-8') + raise e + + return response_data + + 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 + """ + + + 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) + + if not 200 <= response_data.status <= 299: + if response_data.status == 400: + raise BadRequestException(http_resp=response_data) + + if response_data.status == 401: + raise UnauthorizedException(http_resp=response_data) + + if response_data.status == 403: + raise ForbiddenException(http_resp=response_data) + + if response_data.status == 404: + raise NotFoundException(http_resp=response_data) + + if 500 <= response_data.status <= 599: + raise ServiceException(http_resp=response_data) + raise ApiException(http_resp=response_data) + + # deserialize response data + + 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 ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) + + 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. + + :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() + + 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() + } + + def deserialize(self, response_text, response_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + + :return: deserialized object. + """ + + # 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. + """ + 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. + + :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 + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: 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) + + 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)))) + + return "&".join(["=".join(item) for item in new_params]) + + def files_parameters(self, files=None): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + + 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])]) + ) + + return params + + 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 + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns \`Content-Type\` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + 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] + + 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. + """ + if not auth_settings: + return + + 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, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :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\`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the \`Content-Disposition\` header if provided. + + handle file downloading + save response body into a tmp file and return the instance + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + 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) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :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 __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: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse \`{0}\` as datetime object" + .format(string) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) +", + "test_project/api_response.py": """"API response object.""" + +from __future__ import annotations +from typing import Any, Dict, Optional, Generic, TypeVar +from pydantic import Field, StrictInt, StrictStr, StrictBytes, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + 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)") + + model_config = { + "arbitrary_types_allowed": True + } +", + "test_project/configuration.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +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. + + :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. + + """ + + _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 + """ + + 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. + """ + + + 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 + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + 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 __setattr__(self, name, value): + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls): + """Deprecated. Please use \`get_default\` instead. + + Deprecated. Please use \`get_default\` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls): + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = Configuration() + return cls._default + + @property + def logger_file(self): + """The logger file. + + 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 + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + 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 + """ + 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) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :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. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). + + :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 + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :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') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :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 + + :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'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + 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'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None +", + "test_project/exceptions.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + 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) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + 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.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: + """ + 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.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: + """ + 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): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(ServiceException, self).__init__(status, reason, http_resp) + + +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 + +# 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 + +logger = Logger() + +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 + + # 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"]) + + return response + + @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: + """ + 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"] + + # Set the namespace if not set via environment variables + if metrics.namespace is None: + metrics.namespace = operation_id + + request.interceptor_context["metrics"] = metrics + + 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: + """ + 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 + +tracer = Tracer() +is_cold_start = True + +class TracingInterceptor: + def __init__(self, add_response_as_metadata: bool = False): + self._add_response_as_metadata = add_response_as_metadata + + 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 + + operation_id = request.interceptor_context["operationId"] + + 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 + + @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 + +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 + + return response_headers_interceptor + +# Cors interceptor allows all origins and headers. Use build_response_headers_interceptors to customise +cors_interceptor = build_response_headers_interceptor(CORS_HEADERS) + +", + "test_project/interceptors/try_catch.py": "from test_project.api.operation_config import ApiResponse, ChainedApiRequest +from test_project.response import Response + + +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) + + return Response.internal_failure({ "message": "Internal Error" }) +", + "test_project/models/__init__.py": "# coding: utf-8 + +# flake8: noqa +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +# import models into model package +from test_project.models.a import A +from test_project.models.all_of_inline_and_refs import AllOfInlineAndRefs +from test_project.models.all_of_refs import AllOfRefs +from test_project.models.any_of_inline_and_refs import AnyOfInlineAndRefs +from test_project.models.any_of_inline_and_refs_any_of import AnyOfInlineAndRefsAnyOf +from test_project.models.any_of_inline_and_refs_any_of1 import AnyOfInlineAndRefsAnyOf1 +from test_project.models.any_of_primitives import AnyOfPrimitives +from test_project.models.any_of_primitives_and_refs import AnyOfPrimitivesAndRefs +from test_project.models.any_of_refs import AnyOfRefs +from test_project.models.b import B +from test_project.models.c import C +from test_project.models.one_of_inline_and_refs import OneOfInlineAndRefs +from test_project.models.one_of_primitives import OneOfPrimitives +from test_project.models.one_of_primitives_and_refs import OneOfPrimitivesAndRefs +from test_project.models.one_of_refs import OneOfRefs +from test_project.models.wrapper import Wrapper +from test_project.models.wrapper_all_of import WrapperAllOf +from test_project.models.wrapper_any_of import WrapperAnyOf +from test_project.models.wrapper_one_of import WrapperOneOf +", + "test_project/models/a.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class A(BaseModel): + """ + A + """ # noqa: E501 + a: StrictStr + __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 A 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 A 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/models/all_of_inline_and_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AllOfInlineAndRefs(BaseModel): + """ + AllOfInlineAndRefs + """ # noqa: E501 + a: StrictStr + b: StrictStr + c: StrictStr + d: StrictStr + e: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["a", "b", "c", "d", "e"] + + 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 AllOfInlineAndRefs 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 AllOfInlineAndRefs 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"), + "b": obj.get("b"), + "c": obj.get("c"), + "d": obj.get("d"), + "e": obj.get("e") + }) + return _obj + + +", + "test_project/models/all_of_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AllOfRefs(BaseModel): + """ + AllOfRefs + """ # noqa: E501 + a: StrictStr + b: StrictStr + c: StrictStr + __properties: ClassVar[List[str]] = ["a", "b", "c"] + + 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 AllOfRefs 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 AllOfRefs 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"), + "b": obj.get("b"), + "c": obj.get("c") + }) + return _obj + + +", + "test_project/models/any_of_inline_and_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from test_project.models.a import A +from test_project.models.any_of_inline_and_refs_any_of import AnyOfInlineAndRefsAnyOf +from test_project.models.any_of_inline_and_refs_any_of1 import AnyOfInlineAndRefsAnyOf1 +from test_project.models.b import B +from test_project.models.c import C +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ANYOFINLINEANDREFS_ANY_OF_SCHEMAS = ["A", "AnyOfInlineAndRefsAnyOf", "AnyOfInlineAndRefsAnyOf1", "B", "C"] + +class AnyOfInlineAndRefs(BaseModel): + """ + AnyOfInlineAndRefs + """ + + # data type: AnyOfInlineAndRefsAnyOf + anyof_schema_1_validator: Optional[AnyOfInlineAndRefsAnyOf] = None + # data type: A + anyof_schema_2_validator: Optional[A] = None + # data type: B + anyof_schema_3_validator: Optional[B] = None + # data type: C + anyof_schema_4_validator: Optional[C] = None + # data type: AnyOfInlineAndRefsAnyOf1 + anyof_schema_5_validator: Optional[AnyOfInlineAndRefsAnyOf1] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C]] = None + else: + actual_instance: Any = None + any_of_schemas: List[str] = Literal[ANYOFINLINEANDREFS_ANY_OF_SCHEMAS] + + 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_anyof(cls, v): + instance = AnyOfInlineAndRefs.model_construct() + error_messages = [] + # validate data type: AnyOfInlineAndRefsAnyOf + if not isinstance(v, AnyOfInlineAndRefsAnyOf): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`AnyOfInlineAndRefsAnyOf\`") + else: + return v + + # validate data type: A + if not isinstance(v, A): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`A\`") + else: + return v + + # validate data type: B + if not isinstance(v, B): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`B\`") + else: + return v + + # validate data type: C + if not isinstance(v, C): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`C\`") + else: + return v + + # validate data type: AnyOfInlineAndRefsAnyOf1 + if not isinstance(v, AnyOfInlineAndRefsAnyOf1): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`AnyOfInlineAndRefsAnyOf1\`") + else: + return v + + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfInlineAndRefs with anyOf schemas: A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C. 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 = [] + # anyof_schema_1_validator: Optional[AnyOfInlineAndRefsAnyOf] = None + try: + instance.actual_instance = AnyOfInlineAndRefsAnyOf.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # anyof_schema_2_validator: Optional[A] = None + try: + instance.actual_instance = A.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # anyof_schema_3_validator: Optional[B] = None + try: + instance.actual_instance = B.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # anyof_schema_4_validator: Optional[C] = None + try: + instance.actual_instance = C.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # anyof_schema_5_validator: Optional[AnyOfInlineAndRefsAnyOf1] = None + try: + instance.actual_instance = AnyOfInlineAndRefsAnyOf1.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfInlineAndRefs with anyOf schemas: A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C. 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 "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_dict() + else: + return json.dumps(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/any_of_inline_and_refs_any_of.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AnyOfInlineAndRefsAnyOf(BaseModel): + """ + AnyOfInlineAndRefsAnyOf + """ # noqa: E501 + d: StrictStr + __properties: ClassVar[List[str]] = ["d"] + + 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 AnyOfInlineAndRefsAnyOf 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 AnyOfInlineAndRefsAnyOf from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "d": obj.get("d") + }) + return _obj + + +", + "test_project/models/any_of_inline_and_refs_any_of1.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AnyOfInlineAndRefsAnyOf1(BaseModel): + """ + AnyOfInlineAndRefsAnyOf1 + """ # noqa: E501 + e: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["e"] + + 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 AnyOfInlineAndRefsAnyOf1 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 AnyOfInlineAndRefsAnyOf1 from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "e": obj.get("e") + }) + return _obj + + +", + "test_project/models/any_of_primitives.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ANYOFPRIMITIVES_ANY_OF_SCHEMAS = ["int", "str"] + +class AnyOfPrimitives(BaseModel): + """ + AnyOfPrimitives + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: int + anyof_schema_2_validator: Optional[StrictInt] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[int, str]] = None + else: + actual_instance: Any = None + any_of_schemas: List[str] = Literal[ANYOFPRIMITIVES_ANY_OF_SCHEMAS] + + 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_anyof(cls, v): + instance = AnyOfPrimitives.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: int + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfPrimitives with anyOf schemas: int, str. 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into int + try: + # validation + instance.anyof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfPrimitives with anyOf schemas: int, str. 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 "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_dict() + else: + return json.dumps(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/any_of_primitives_and_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from test_project.models.a import A +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ANYOFPRIMITIVESANDREFS_ANY_OF_SCHEMAS = ["A", "str"] + +class AnyOfPrimitivesAndRefs(BaseModel): + """ + AnyOfPrimitivesAndRefs + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: A + anyof_schema_2_validator: Optional[A] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[A, str]] = None + else: + actual_instance: Any = None + any_of_schemas: List[str] = Literal[ANYOFPRIMITIVESANDREFS_ANY_OF_SCHEMAS] + + 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_anyof(cls, v): + instance = AnyOfPrimitivesAndRefs.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: A + if not isinstance(v, A): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`A\`") + else: + return v + + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfPrimitivesAndRefs with anyOf schemas: A, str. 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # anyof_schema_2_validator: Optional[A] = None + try: + instance.actual_instance = A.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfPrimitivesAndRefs with anyOf schemas: A, str. 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 "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_dict() + else: + return json.dumps(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/any_of_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from test_project.models.a import A +from test_project.models.b import B +from test_project.models.c import C +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ANYOFREFS_ANY_OF_SCHEMAS = ["A", "B", "C"] + +class AnyOfRefs(BaseModel): + """ + AnyOfRefs + """ + + # data type: A + anyof_schema_1_validator: Optional[A] = None + # data type: B + anyof_schema_2_validator: Optional[B] = None + # data type: C + anyof_schema_3_validator: Optional[C] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[A, B, C]] = None + else: + actual_instance: Any = None + any_of_schemas: List[str] = Literal[ANYOFREFS_ANY_OF_SCHEMAS] + + 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_anyof(cls, v): + instance = AnyOfRefs.model_construct() + error_messages = [] + # validate data type: A + if not isinstance(v, A): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`A\`") + else: + return v + + # validate data type: B + if not isinstance(v, B): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`B\`") + else: + return v + + # validate data type: C + if not isinstance(v, C): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`C\`") + else: + return v + + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfRefs with anyOf schemas: A, B, C. 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 = [] + # anyof_schema_1_validator: Optional[A] = None + try: + instance.actual_instance = A.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # anyof_schema_2_validator: Optional[B] = None + try: + instance.actual_instance = B.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # anyof_schema_3_validator: Optional[C] = None + try: + instance.actual_instance = C.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfRefs with anyOf schemas: A, B, C. 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 "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_dict() + else: + return json.dumps(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/b.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class B(BaseModel): + """ + B + """ # noqa: E501 + b: StrictStr + __properties: ClassVar[List[str]] = ["b"] + + 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 B 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 B from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "b": obj.get("b") + }) + return _obj + + +", + "test_project/models/c.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class C(BaseModel): + """ + C + """ # noqa: E501 + c: StrictStr + __properties: ClassVar[List[str]] = ["c"] + + 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 C 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 C from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "c": obj.get("c") + }) + return _obj + + +", + "test_project/models/one_of_inline_and_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from test_project.models.a import A +from test_project.models.any_of_inline_and_refs_any_of import AnyOfInlineAndRefsAnyOf +from test_project.models.any_of_inline_and_refs_any_of1 import AnyOfInlineAndRefsAnyOf1 +from test_project.models.b import B +from test_project.models.c import C +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ONEOFINLINEANDREFS_ONE_OF_SCHEMAS = ["A", "AnyOfInlineAndRefsAnyOf", "AnyOfInlineAndRefsAnyOf1", "B", "C"] + +class OneOfInlineAndRefs(BaseModel): + """ + OneOfInlineAndRefs + """ + # data type: AnyOfInlineAndRefsAnyOf + oneof_schema_1_validator: Optional[AnyOfInlineAndRefsAnyOf] = None + # data type: A + oneof_schema_2_validator: Optional[A] = None + # data type: B + oneof_schema_3_validator: Optional[B] = None + # data type: C + oneof_schema_4_validator: Optional[C] = None + # data type: AnyOfInlineAndRefsAnyOf1 + oneof_schema_5_validator: Optional[AnyOfInlineAndRefsAnyOf1] = None + actual_instance: Optional[Union[A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C]] = None + one_of_schemas: List[str] = Literal["A", "AnyOfInlineAndRefsAnyOf", "AnyOfInlineAndRefsAnyOf1", "B", "C"] + + 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 = OneOfInlineAndRefs.model_construct() + error_messages = [] + match = 0 + # validate data type: AnyOfInlineAndRefsAnyOf + if not isinstance(v, AnyOfInlineAndRefsAnyOf): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`AnyOfInlineAndRefsAnyOf\`") + else: + match += 1 + # validate data type: A + if not isinstance(v, A): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`A\`") + else: + match += 1 + # validate data type: B + if not isinstance(v, B): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`B\`") + else: + match += 1 + # validate data type: C + if not isinstance(v, C): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`C\`") + else: + match += 1 + # validate data type: AnyOfInlineAndRefsAnyOf1 + if not isinstance(v, AnyOfInlineAndRefsAnyOf1): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`AnyOfInlineAndRefsAnyOf1\`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting \`actual_instance\` in OneOfInlineAndRefs with oneOf schemas: A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting \`actual_instance\` in OneOfInlineAndRefs with oneOf schemas: A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C. 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 AnyOfInlineAndRefsAnyOf + try: + instance.actual_instance = AnyOfInlineAndRefsAnyOf.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into A + try: + instance.actual_instance = A.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into B + try: + instance.actual_instance = B.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into C + try: + instance.actual_instance = C.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into AnyOfInlineAndRefsAnyOf1 + try: + instance.actual_instance = AnyOfInlineAndRefsAnyOf1.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 OneOfInlineAndRefs with oneOf schemas: A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfInlineAndRefs with oneOf schemas: A, AnyOfInlineAndRefsAnyOf, AnyOfInlineAndRefsAnyOf1, B, C. 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/one_of_primitives.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ONEOFPRIMITIVES_ONE_OF_SCHEMAS = ["int", "str"] + +class OneOfPrimitives(BaseModel): + """ + OneOfPrimitives + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: int + oneof_schema_2_validator: Optional[StrictInt] = None + actual_instance: Optional[Union[int, str]] = None + one_of_schemas: List[str] = Literal["int", "str"] + + 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 = OneOfPrimitives.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: int + try: + instance.oneof_schema_2_validator = v + 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 setting \`actual_instance\` in OneOfPrimitives with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting \`actual_instance\` in OneOfPrimitives with oneOf schemas: int, str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into int + try: + # validation + instance.oneof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + 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 OneOfPrimitives with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfPrimitives with oneOf schemas: int, str. 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/one_of_primitives_and_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from test_project.models.a import A +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ONEOFPRIMITIVESANDREFS_ONE_OF_SCHEMAS = ["A", "str"] + +class OneOfPrimitivesAndRefs(BaseModel): + """ + OneOfPrimitivesAndRefs + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: A + oneof_schema_2_validator: Optional[A] = None + actual_instance: Optional[Union[A, str]] = None + one_of_schemas: List[str] = Literal["A", "str"] + + 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 = OneOfPrimitivesAndRefs.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: A + if not isinstance(v, A): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`A\`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting \`actual_instance\` in OneOfPrimitivesAndRefs with oneOf schemas: A, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting \`actual_instance\` in OneOfPrimitivesAndRefs with oneOf schemas: A, str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into A + try: + instance.actual_instance = A.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 OneOfPrimitivesAndRefs with oneOf schemas: A, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfPrimitivesAndRefs with oneOf schemas: A, str. 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/one_of_refs.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from test_project.models.a import A +from test_project.models.b import B +from test_project.models.c import C +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +ONEOFREFS_ONE_OF_SCHEMAS = ["A", "B", "C"] + +class OneOfRefs(BaseModel): + """ + OneOfRefs + """ + # data type: A + oneof_schema_1_validator: Optional[A] = None + # data type: B + oneof_schema_2_validator: Optional[B] = None + # data type: C + oneof_schema_3_validator: Optional[C] = None + actual_instance: Optional[Union[A, B, C]] = None + one_of_schemas: List[str] = Literal["A", "B", "C"] + + 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 = OneOfRefs.model_construct() + error_messages = [] + match = 0 + # validate data type: A + if not isinstance(v, A): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`A\`") + else: + match += 1 + # validate data type: B + if not isinstance(v, B): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`B\`") + else: + match += 1 + # validate data type: C + if not isinstance(v, C): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`C\`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting \`actual_instance\` in OneOfRefs with oneOf schemas: A, B, C. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting \`actual_instance\` in OneOfRefs with oneOf schemas: A, B, C. 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 A + try: + instance.actual_instance = A.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into B + try: + instance.actual_instance = B.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into C + try: + instance.actual_instance = C.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 OneOfRefs with oneOf schemas: A, B, C. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfRefs with oneOf schemas: A, B, C. 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/wrapper.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from pydantic import Field +from test_project.models.wrapper_all_of import WrapperAllOf +from test_project.models.wrapper_any_of import WrapperAnyOf +from test_project.models.wrapper_one_of import WrapperOneOf +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Wrapper(BaseModel): + """ + Wrapper + """ # noqa: E501 + all_of: Optional[WrapperAllOf] = Field(default=None, alias="allOf") + any_of: Optional[WrapperAnyOf] = Field(default=None, alias="anyOf") + one_of: Optional[WrapperOneOf] = Field(default=None, alias="oneOf") + __properties: ClassVar[List[str]] = ["allOf", "anyOf", "oneOf"] + + 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 Wrapper 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, + ) + # override the default output from pydantic by calling \`to_dict()\` of all_of + if self.all_of: + _dict['allOf'] = self.all_of.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of any_of + if self.any_of: + _dict['anyOf'] = self.any_of.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of one_of + if self.one_of: + _dict['oneOf'] = self.one_of.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Wrapper from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "allOf": WrapperAllOf.from_dict(obj.get("allOf")) if obj.get("allOf") is not None else None, + "anyOf": WrapperAnyOf.from_dict(obj.get("anyOf")) if obj.get("anyOf") is not None else None, + "oneOf": WrapperOneOf.from_dict(obj.get("oneOf")) if obj.get("oneOf") is not None else None + }) + return _obj + + +", + "test_project/models/wrapper_all_of.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from pydantic import Field +from test_project.models.all_of_inline_and_refs import AllOfInlineAndRefs +from test_project.models.all_of_refs import AllOfRefs +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class WrapperAllOf(BaseModel): + """ + WrapperAllOf + """ # noqa: E501 + refs: Optional[AllOfRefs] = None + inline_and_refs: Optional[AllOfInlineAndRefs] = Field(default=None, alias="inlineAndRefs") + __properties: ClassVar[List[str]] = ["refs", "inlineAndRefs"] + + 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 WrapperAllOf 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, + ) + # override the default output from pydantic by calling \`to_dict()\` of refs + if self.refs: + _dict['refs'] = self.refs.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of inline_and_refs + if self.inline_and_refs: + _dict['inlineAndRefs'] = self.inline_and_refs.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of WrapperAllOf from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "refs": AllOfRefs.from_dict(obj.get("refs")) if obj.get("refs") is not None else None, + "inlineAndRefs": AllOfInlineAndRefs.from_dict(obj.get("inlineAndRefs")) if obj.get("inlineAndRefs") is not None else None + }) + return _obj + + +", + "test_project/models/wrapper_any_of.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from pydantic import Field +from test_project.models.any_of_inline_and_refs import AnyOfInlineAndRefs +from test_project.models.any_of_primitives import AnyOfPrimitives +from test_project.models.any_of_primitives_and_refs import AnyOfPrimitivesAndRefs +from test_project.models.any_of_refs import AnyOfRefs +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class WrapperAnyOf(BaseModel): + """ + WrapperAnyOf + """ # noqa: E501 + refs: Optional[AnyOfRefs] = None + inline_and_refs: Optional[AnyOfInlineAndRefs] = Field(default=None, alias="inlineAndRefs") + primitives: Optional[AnyOfPrimitives] = None + primitives_and_refs: Optional[AnyOfPrimitivesAndRefs] = Field(default=None, alias="primitivesAndRefs") + __properties: ClassVar[List[str]] = ["refs", "inlineAndRefs", "primitives", "primitivesAndRefs"] + + 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 WrapperAnyOf 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, + ) + # override the default output from pydantic by calling \`to_dict()\` of refs + if self.refs: + _dict['refs'] = self.refs.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of inline_and_refs + if self.inline_and_refs: + _dict['inlineAndRefs'] = self.inline_and_refs.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of primitives + if self.primitives: + _dict['primitives'] = self.primitives.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of primitives_and_refs + if self.primitives_and_refs: + _dict['primitivesAndRefs'] = self.primitives_and_refs.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of WrapperAnyOf from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "refs": AnyOfRefs.from_dict(obj.get("refs")) if obj.get("refs") is not None else None, + "inlineAndRefs": AnyOfInlineAndRefs.from_dict(obj.get("inlineAndRefs")) if obj.get("inlineAndRefs") is not None else None, + "primitives": AnyOfPrimitives.from_dict(obj.get("primitives")) if obj.get("primitives") is not None else None, + "primitivesAndRefs": AnyOfPrimitivesAndRefs.from_dict(obj.get("primitivesAndRefs")) if obj.get("primitivesAndRefs") is not None else None + }) + return _obj + + +", + "test_project/models/wrapper_one_of.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from pydantic import Field +from test_project.models.one_of_inline_and_refs import OneOfInlineAndRefs +from test_project.models.one_of_primitives import OneOfPrimitives +from test_project.models.one_of_primitives_and_refs import OneOfPrimitivesAndRefs +from test_project.models.one_of_refs import OneOfRefs +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class WrapperOneOf(BaseModel): + """ + WrapperOneOf + """ # noqa: E501 + refs: Optional[OneOfRefs] = None + inline_and_refs: Optional[OneOfInlineAndRefs] = Field(default=None, alias="inlineAndRefs") + primitives: Optional[OneOfPrimitives] = None + primitives_and_refs: Optional[OneOfPrimitivesAndRefs] = Field(default=None, alias="primitivesAndRefs") + __properties: ClassVar[List[str]] = ["refs", "inlineAndRefs", "primitives", "primitivesAndRefs"] + + 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 WrapperOneOf 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, + ) + # override the default output from pydantic by calling \`to_dict()\` of refs + if self.refs: + _dict['refs'] = self.refs.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of inline_and_refs + if self.inline_and_refs: + _dict['inlineAndRefs'] = self.inline_and_refs.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of primitives + if self.primitives: + _dict['primitives'] = self.primitives.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of primitives_and_refs + if self.primitives_and_refs: + _dict['primitivesAndRefs'] = self.primitives_and_refs.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of WrapperOneOf from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "refs": OneOfRefs.from_dict(obj.get("refs")) if obj.get("refs") is not None else None, + "inlineAndRefs": OneOfInlineAndRefs.from_dict(obj.get("inlineAndRefs")) if obj.get("inlineAndRefs") is not None else None, + "primitives": OneOfPrimitives.from_dict(obj.get("primitives")) if obj.get("primitives") is not None else None, + "primitivesAndRefs": OneOfPrimitivesAndRefs.from_dict(obj.get("primitivesAndRefs")) if obj.get("primitivesAndRefs") is not None else None + }) + return _obj + + +", + "test_project/py.typed": "", + "test_project/response.py": "from typing import TypeVar, Generic, Dict, List +from test_project.api.operation_config import ApiResponse + +ResponseBody = TypeVar("ResponseBody") + +class Response(Generic[ResponseBody]): + """ + Helpers for constructing api responses + """ + + @staticmethod + def success(body: ResponseBody, headers: Dict[str, str] = {}, multi_value_headers: Dict[str, List[str]] = {}) -> ApiResponse[200, ResponseBody]: + """ + A successful response + """ + return ApiResponse(status_code=200, body=body, headers={**headers}, multi_value_headers={**multi_value_headers}) + + @staticmethod + def bad_request(body: ResponseBody, headers: Dict[str, str] = {}, multi_value_headers: Dict[str, List[str]] = {}) -> ApiResponse[400, ResponseBody]: + """ + A response which indicates a client error + """ + return ApiResponse(status_code=400, body=body, headers={**headers}, multi_value_headers={**multi_value_headers}) + + @staticmethod + def not_found(body: ResponseBody, headers: Dict[str, str] = {}, multi_value_headers: Dict[str, List[str]] = {}) -> ApiResponse[404, ResponseBody]: + """ + A response which indicates the requested resource was not found + """ + return ApiResponse(status_code=404, body=body, headers={**headers}, multi_value_headers={**multi_value_headers}) + + @staticmethod + def not_authorized(body: ResponseBody, headers: Dict[str, str] = {}, multi_value_headers: Dict[str, List[str]] = {}) -> ApiResponse[403, ResponseBody]: + """ + A response which indicates the caller is not authorised to perform the operation or access the resource + """ + return ApiResponse(status_code=403, body=body, headers={**headers}, multi_value_headers={**multi_value_headers}) + + @staticmethod + def internal_failure(body: ResponseBody, headers: Dict[str, str] = {}, multi_value_headers: Dict[str, List[str]] = {}) -> ApiResponse[500, ResponseBody]: + """ + A response to indicate a server error + """ + return ApiResponse(status_code=500, body=body, headers={**headers}, multi_value_headers={**multi_value_headers}) +", + "test_project/rest.py": "# coding: utf-8 + +""" + composite models + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import re +import ssl + +import urllib3 + +from test_project.exceptions import ApiException, ApiValueError + +RESTResponseType = urllib3.HTTPResponse + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + addition_pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + addition_pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + addition_pool_args['socket_options'] = configuration.socket_options + + # https pool manager + if configuration.proxy: + self.pool_manager = urllib3.ProxyManager( + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for \`application/json\` + :param post_params: request post parameters, + \`application/x-www-form-urlencoded\` + and \`multipart/form-data\` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For \`POST\`, \`PUT\`, \`PATCH\`, \`OPTIONS\`, \`DELETE\` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a \`string\` parameter directly in the body to support + # other content types than Json when \`body\` argument is + # provided in serialized form + elif isinstance(body, str) or isinstance(body, bytes): + request_body = body + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For \`GET\`, \`HEAD\` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) +", +} +`; + exports[`Python Client Code Generation Script Unit Tests Generates With data-types.yaml 1`] = ` { ".gitattributes": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". @@ -3588,6 +9667,9 @@ docs/DataTypes200Response.md docs/DataTypes200ResponseMyAllOf.md docs/DataTypes200ResponseMyAnyOf.md docs/DataTypes200ResponseMyNotNot.md +docs/DataTypes200ResponseMyObject.md +docs/DataTypes200ResponseMyObjectOne.md +docs/DataTypes200ResponseMyObjectOneTwo.md docs/DataTypes200ResponseMyOneOf.md docs/DefaultApi.md test_project/__init__.py @@ -3604,6 +9686,9 @@ test_project/models/data_types200_response.py test_project/models/data_types200_response_my_all_of.py test_project/models/data_types200_response_my_any_of.py test_project/models/data_types200_response_my_not_not.py +test_project/models/data_types200_response_my_object.py +test_project/models/data_types200_response_my_object_one.py +test_project/models/data_types200_response_my_object_one_two.py test_project/models/data_types200_response_my_one_of.py test_project/py.typed test_project/response.py @@ -3954,6 +10039,9 @@ Class | Method | HTTP request | Description - [DataTypes200ResponseMyAllOf](docs/DataTypes200ResponseMyAllOf.md) - [DataTypes200ResponseMyAnyOf](docs/DataTypes200ResponseMyAnyOf.md) - [DataTypes200ResponseMyNotNot](docs/DataTypes200ResponseMyNotNot.md) + - [DataTypes200ResponseMyObject](docs/DataTypes200ResponseMyObject.md) + - [DataTypes200ResponseMyObjectOne](docs/DataTypes200ResponseMyObjectOne.md) + - [DataTypes200ResponseMyObjectOneTwo](docs/DataTypes200ResponseMyObjectOneTwo.md) - [DataTypes200ResponseMyOneOf](docs/DataTypes200ResponseMyOneOf.md) @@ -3997,6 +10085,7 @@ Name | Type | Description | Notes **my_not** | **object** | | [optional] **my_not_string** | **object** | | [optional] **my_additional_properties** | **Dict[str, List[int]]** | | [optional] +**my_object** | [**DataTypes200ResponseMyObject**](DataTypes200ResponseMyObject.md) | | [optional] ## Example @@ -4066,41 +10155,130 @@ json = "{}" # create an instance of DataTypes200ResponseMyAnyOf from a JSON string data_types200_response_my_any_of_instance = DataTypes200ResponseMyAnyOf.from_json(json) # print the JSON string representation of the object -print DataTypes200ResponseMyAnyOf.to_json() +print DataTypes200ResponseMyAnyOf.to_json() + +# convert the object into a dict +data_types200_response_my_any_of_dict = data_types200_response_my_any_of_instance.to_dict() +# create an instance of DataTypes200ResponseMyAnyOf from a dict +data_types200_response_my_any_of_form_dict = data_types200_response_my_any_of.from_dict(data_types200_response_my_any_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/DataTypes200ResponseMyNotNot.md": "# DataTypes200ResponseMyNotNot + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.data_types200_response_my_not_not import DataTypes200ResponseMyNotNot + +# TODO update the JSON string below +json = "{}" +# create an instance of DataTypes200ResponseMyNotNot from a JSON string +data_types200_response_my_not_not_instance = DataTypes200ResponseMyNotNot.from_json(json) +# print the JSON string representation of the object +print DataTypes200ResponseMyNotNot.to_json() + +# convert the object into a dict +data_types200_response_my_not_not_dict = data_types200_response_my_not_not_instance.to_dict() +# create an instance of DataTypes200ResponseMyNotNot from a dict +data_types200_response_my_not_not_form_dict = data_types200_response_my_not_not.from_dict(data_types200_response_my_not_not_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/DataTypes200ResponseMyObject.md": "# DataTypes200ResponseMyObject + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**one** | [**DataTypes200ResponseMyObjectOne**](DataTypes200ResponseMyObjectOne.md) | | [optional] +**one_string** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.data_types200_response_my_object import DataTypes200ResponseMyObject + +# TODO update the JSON string below +json = "{}" +# create an instance of DataTypes200ResponseMyObject from a JSON string +data_types200_response_my_object_instance = DataTypes200ResponseMyObject.from_json(json) +# print the JSON string representation of the object +print DataTypes200ResponseMyObject.to_json() + +# convert the object into a dict +data_types200_response_my_object_dict = data_types200_response_my_object_instance.to_dict() +# create an instance of DataTypes200ResponseMyObject from a dict +data_types200_response_my_object_form_dict = data_types200_response_my_object.from_dict(data_types200_response_my_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) + + +", + "docs/DataTypes200ResponseMyObjectOne.md": "# DataTypes200ResponseMyObjectOne + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**two_string** | **str** | | [optional] +**two** | [**DataTypes200ResponseMyObjectOneTwo**](DataTypes200ResponseMyObjectOneTwo.md) | | [optional] + +## Example + +\`\`\`python +from test_project.models.data_types200_response_my_object_one import DataTypes200ResponseMyObjectOne + +# TODO update the JSON string below +json = "{}" +# create an instance of DataTypes200ResponseMyObjectOne from a JSON string +data_types200_response_my_object_one_instance = DataTypes200ResponseMyObjectOne.from_json(json) +# print the JSON string representation of the object +print DataTypes200ResponseMyObjectOne.to_json() # convert the object into a dict -data_types200_response_my_any_of_dict = data_types200_response_my_any_of_instance.to_dict() -# create an instance of DataTypes200ResponseMyAnyOf from a dict -data_types200_response_my_any_of_form_dict = data_types200_response_my_any_of.from_dict(data_types200_response_my_any_of_dict) +data_types200_response_my_object_one_dict = data_types200_response_my_object_one_instance.to_dict() +# create an instance of DataTypes200ResponseMyObjectOne from a dict +data_types200_response_my_object_one_form_dict = data_types200_response_my_object_one.from_dict(data_types200_response_my_object_one_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/DataTypes200ResponseMyNotNot.md": "# DataTypes200ResponseMyNotNot + "docs/DataTypes200ResponseMyObjectOneTwo.md": "# DataTypes200ResponseMyObjectOneTwo ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**foo** | **str** | | [optional] +**three_string** | **str** | | [optional] ## Example \`\`\`python -from test_project.models.data_types200_response_my_not_not import DataTypes200ResponseMyNotNot +from test_project.models.data_types200_response_my_object_one_two import DataTypes200ResponseMyObjectOneTwo # TODO update the JSON string below json = "{}" -# create an instance of DataTypes200ResponseMyNotNot from a JSON string -data_types200_response_my_not_not_instance = DataTypes200ResponseMyNotNot.from_json(json) +# create an instance of DataTypes200ResponseMyObjectOneTwo from a JSON string +data_types200_response_my_object_one_two_instance = DataTypes200ResponseMyObjectOneTwo.from_json(json) # print the JSON string representation of the object -print DataTypes200ResponseMyNotNot.to_json() +print DataTypes200ResponseMyObjectOneTwo.to_json() # convert the object into a dict -data_types200_response_my_not_not_dict = data_types200_response_my_not_not_instance.to_dict() -# create an instance of DataTypes200ResponseMyNotNot from a dict -data_types200_response_my_not_not_form_dict = data_types200_response_my_not_not.from_dict(data_types200_response_my_not_not_dict) +data_types200_response_my_object_one_two_dict = data_types200_response_my_object_one_two_instance.to_dict() +# create an instance of DataTypes200ResponseMyObjectOneTwo from a dict +data_types200_response_my_object_one_two_form_dict = data_types200_response_my_object_one_two.from_dict(data_types200_response_my_object_one_two_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) @@ -4255,6 +10433,9 @@ from test_project.models.data_types200_response import DataTypes200Response from test_project.models.data_types200_response_my_all_of import DataTypes200ResponseMyAllOf from test_project.models.data_types200_response_my_any_of import DataTypes200ResponseMyAnyOf from test_project.models.data_types200_response_my_not_not import DataTypes200ResponseMyNotNot +from test_project.models.data_types200_response_my_object import DataTypes200ResponseMyObject +from test_project.models.data_types200_response_my_object_one import DataTypes200ResponseMyObjectOne +from test_project.models.data_types200_response_my_object_one_two import DataTypes200ResponseMyObjectOneTwo from test_project.models.data_types200_response_my_one_of import DataTypes200ResponseMyOneOf ", "test_project/api/__init__.py": "# flake8: noqa @@ -6440,6 +12621,9 @@ from test_project.models.data_types200_response import DataTypes200Response from test_project.models.data_types200_response_my_all_of import DataTypes200ResponseMyAllOf from test_project.models.data_types200_response_my_any_of import DataTypes200ResponseMyAnyOf from test_project.models.data_types200_response_my_not_not import DataTypes200ResponseMyNotNot +from test_project.models.data_types200_response_my_object import DataTypes200ResponseMyObject +from test_project.models.data_types200_response_my_object_one import DataTypes200ResponseMyObjectOne +from test_project.models.data_types200_response_my_object_one_two import DataTypes200ResponseMyObjectOneTwo from test_project.models.data_types200_response_my_one_of import DataTypes200ResponseMyOneOf ", "test_project/models/data_types200_response.py": "# coding: utf-8 @@ -6468,6 +12652,7 @@ from pydantic import Field from typing_extensions import Annotated from test_project.models.data_types200_response_my_all_of import DataTypes200ResponseMyAllOf from test_project.models.data_types200_response_my_any_of import DataTypes200ResponseMyAnyOf +from test_project.models.data_types200_response_my_object import DataTypes200ResponseMyObject from test_project.models.data_types200_response_my_one_of import DataTypes200ResponseMyOneOf try: from typing import Self @@ -6500,7 +12685,8 @@ class DataTypes200Response(BaseModel): my_not: Optional[Any] = Field(default=None, alias="myNot") my_not_string: Optional[Any] = Field(default=None, alias="myNotString") my_additional_properties: Optional[Dict[str, Annotated[List[Annotated[int, Field(le=20, strict=True, ge=10)]], Field(min_length=2, max_length=5)]]] = Field(default=None, alias="myAdditionalProperties") - __properties: ClassVar[List[str]] = ["myInt", "myString", "myStringLength", "myLongMinStringLength", "myBool", "myNumber", "myDateArray", "myEmail", "myUrl", "myHostname", "myIpv4", "myIpv6", "myUuid", "myByte", "myDateTime", "myRegexPattern", "myOneOf", "myAnyOf", "myAllOf", "myNot", "myNotString", "myAdditionalProperties"] + my_object: Optional[DataTypes200ResponseMyObject] = Field(default=None, alias="myObject") + __properties: ClassVar[List[str]] = ["myInt", "myString", "myStringLength", "myLongMinStringLength", "myBool", "myNumber", "myDateArray", "myEmail", "myUrl", "myHostname", "myIpv4", "myIpv6", "myUuid", "myByte", "myDateTime", "myRegexPattern", "myOneOf", "myAnyOf", "myAllOf", "myNot", "myNotString", "myAdditionalProperties", "myObject"] @field_validator('my_regex_pattern') def my_regex_pattern_validate_regular_expression(cls, value): @@ -6557,6 +12743,9 @@ class DataTypes200Response(BaseModel): # override the default output from pydantic by calling \`to_dict()\` of my_all_of if self.my_all_of: _dict['myAllOf'] = self.my_all_of.to_dict() + # override the default output from pydantic by calling \`to_dict()\` of my_object + if self.my_object: + _dict['myObject'] = self.my_object.to_dict() # set to None if my_not (nullable) is None # and model_fields_set contains the field if self.my_not is None and "my_not" in self.model_fields_set: @@ -6600,7 +12789,8 @@ class DataTypes200Response(BaseModel): "myAllOf": DataTypes200ResponseMyAllOf.from_dict(obj.get("myAllOf")) if obj.get("myAllOf") is not None else None, "myNot": obj.get("myNot"), "myNotString": obj.get("myNotString"), - "myAdditionalProperties": obj.get("myAdditionalProperties") + "myAdditionalProperties": obj.get("myAdditionalProperties"), + "myObject": DataTypes200ResponseMyObject.from_dict(obj.get("myObject")) if obj.get("myObject") is not None else None }) return _obj @@ -6928,6 +13118,285 @@ class DataTypes200ResponseMyNotNot(BaseModel): return _obj +", + "test_project/models/data_types200_response_my_object.py": "# coding: utf-8 + +""" + Data Types + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from pydantic import Field +from test_project.models.data_types200_response_my_object_one import DataTypes200ResponseMyObjectOne +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class DataTypes200ResponseMyObject(BaseModel): + """ + DataTypes200ResponseMyObject + """ # noqa: E501 + one: Optional[DataTypes200ResponseMyObjectOne] = None + one_string: Optional[StrictStr] = Field(default=None, alias="oneString") + __properties: ClassVar[List[str]] = ["one", "oneString"] + + 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 DataTypes200ResponseMyObject 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, + ) + # override the default output from pydantic by calling \`to_dict()\` of one + if self.one: + _dict['one'] = self.one.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of DataTypes200ResponseMyObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "one": DataTypes200ResponseMyObjectOne.from_dict(obj.get("one")) if obj.get("one") is not None else None, + "oneString": obj.get("oneString") + }) + return _obj + + +", + "test_project/models/data_types200_response_my_object_one.py": "# coding: utf-8 + +""" + Data Types + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from pydantic import Field +from test_project.models.data_types200_response_my_object_one_two import DataTypes200ResponseMyObjectOneTwo +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class DataTypes200ResponseMyObjectOne(BaseModel): + """ + DataTypes200ResponseMyObjectOne + """ # noqa: E501 + two_string: Optional[StrictStr] = Field(default=None, alias="twoString") + two: Optional[DataTypes200ResponseMyObjectOneTwo] = None + __properties: ClassVar[List[str]] = ["twoString", "two"] + + 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 DataTypes200ResponseMyObjectOne 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, + ) + # override the default output from pydantic by calling \`to_dict()\` of two + if self.two: + _dict['two'] = self.two.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of DataTypes200ResponseMyObjectOne from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "twoString": obj.get("twoString"), + "two": DataTypes200ResponseMyObjectOneTwo.from_dict(obj.get("two")) if obj.get("two") is not None else None + }) + return _obj + + +", + "test_project/models/data_types200_response_my_object_one_two.py": "# coding: utf-8 + +""" + Data Types + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from pydantic import Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class DataTypes200ResponseMyObjectOneTwo(BaseModel): + """ + DataTypes200ResponseMyObjectOneTwo + """ # noqa: E501 + three_string: Optional[StrictStr] = Field(default=None, alias="threeString") + __properties: ClassVar[List[str]] = ["threeString"] + + 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 DataTypes200ResponseMyObjectOneTwo 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 DataTypes200ResponseMyObjectOneTwo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "threeString": obj.get("threeString") + }) + return _obj + + ", "test_project/models/data_types200_response_my_one_of.py": "# coding: utf-8 diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript-react-query-hooks.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript-react-query-hooks.test.ts.snap index cd1f44361..99f38747d 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript-react-query-hooks.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript-react-query-hooks.test.ts.snap @@ -1676,7 +1676,6 @@ export interface ApiError { export function instanceOfApiError(value: object): boolean { let isInstance = true; isInstance = isInstance && "errorMessage" in value; - return isInstance; } @@ -1748,7 +1747,6 @@ export interface PaginatedGet200Response { */ export function instanceOfPaginatedGet200Response(value: object): boolean { let isInstance = true; - return isInstance; } @@ -1816,7 +1814,6 @@ export interface RegularGet200Response { */ export function instanceOfRegularGet200Response(value: object): boolean { let isInstance = true; - return isInstance; } @@ -1882,7 +1879,6 @@ export interface TestRequest { */ export function instanceOfTestRequest(value: object): boolean { let isInstance = true; - return isInstance; } @@ -1932,6 +1928,7 @@ import { TestResponseMessagesInnerFromJSON, TestResponseMessagesInnerFromJSONTyped, TestResponseMessagesInnerToJSON, + instanceOfTestResponseMessagesInner, } from './TestResponseMessagesInner'; /** @@ -1955,7 +1952,6 @@ export interface TestResponse { export function instanceOfTestResponse(value: object): boolean { let isInstance = true; isInstance = isInstance && "messages" in value; - return isInstance; } @@ -2028,7 +2024,6 @@ export interface TestResponseMessagesInner { export function instanceOfTestResponseMessagesInner(value: object): boolean { let isInstance = true; isInstance = isInstance && "id" in value; - return isInstance; } 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 54fbd10df..cc27dd297 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 @@ -784,43 +784,29 @@ import { TemplateBaseFromJSON, TemplateBaseFromJSONTyped, TemplateBaseToJSON, + instanceOfTemplateBase, } from './TemplateBase'; import type { TemplateBody } from './TemplateBody'; import { TemplateBodyFromJSON, TemplateBodyFromJSONTyped, TemplateBodyToJSON, + instanceOfTemplateBody, } from './TemplateBody'; -import type { TemplateID } from './TemplateID'; -import { - TemplateIDFromJSON, - TemplateIDFromJSONTyped, - TemplateIDToJSON, -} from './TemplateID'; /** + * @type Template * * @export - * @interface Template */ -export interface Template { - /** - * - * @type {TemplateID} - * @memberof Template - */ - id: TemplateID; -} +export type Template = TemplateBase & TemplateBody; /** * Check if a given object implements the Template interface. */ export function instanceOfTemplate(value: object): boolean { - let isInstance = true; - isInstance = isInstance && "id" in value; - - return isInstance; + return instanceOfTemplateBase(value) && instanceOfTemplateBody(value) } export function TemplateFromJSON(json: any): Template { @@ -832,8 +818,8 @@ export function TemplateFromJSONTyped(json: any, ignoreDiscriminator: boolean): return json; } return { - - 'id': TemplateIDFromJSON(json['id']), + ...TemplateBaseFromJSONTyped(json, true), + ...TemplateBodyFromJSONTyped(json, true), }; } @@ -845,8 +831,8 @@ export function TemplateToJSON(value?: Template | null): any { return null; } return { - - 'id': TemplateIDToJSON(value.id), + ...TemplateBaseToJSON(value as any), + ...TemplateBodyToJSON(value as any), }; } @@ -869,6 +855,7 @@ import { TemplateIDFromJSON, TemplateIDFromJSONTyped, TemplateIDToJSON, + instanceOfTemplateID, } from './TemplateID'; /** @@ -893,7 +880,6 @@ export interface TemplateBase { export function instanceOfTemplateBase(value: object): boolean { let isInstance = true; isInstance = isInstance && "id" in value; - return isInstance; } @@ -943,6 +929,7 @@ import { TemplateIDFromJSON, TemplateIDFromJSONTyped, TemplateIDToJSON, + instanceOfTemplateID, } from './TemplateID'; /** @@ -972,7 +959,6 @@ export interface TemplateBody { */ export function instanceOfTemplateBody(value: object): boolean { let isInstance = true; - return isInstance; } @@ -1034,7 +1020,6 @@ export interface TemplateID { */ export function instanceOfTemplateID(value: object): boolean { let isInstance = true; - return isInstance; } @@ -1540,7 +1525,7 @@ export class TextApiResponse { } `; -exports[`Typescript Client Code Generation Script Unit Tests Generates With data-types.yaml 1`] = ` +exports[`Typescript Client Code Generation Script Unit Tests Generates With composite-models.yaml 1`] = ` { ".tsapi-manifest": "src/index.ts src/runtime.ts @@ -1556,11 +1541,33 @@ src/apis/DefaultApi.ts src/apis/index.ts src/models/index.ts src/models/model-utils.ts -src/models/DataTypes200Response.ts", +src/models/A.ts +src/models/AllOfInlineAndRefs.ts +src/models/AllOfInlineAndRefsAllOf.ts +src/models/AllOfInlineAndRefsAllOf1.ts +src/models/AllOfRefs.ts +src/models/AnyOfInlineAndRefs.ts +src/models/AnyOfInlineAndRefsAnyOf.ts +src/models/AnyOfInlineAndRefsAnyOf1.ts +src/models/AnyOfPrimitives.ts +src/models/AnyOfPrimitivesAndRefs.ts +src/models/AnyOfRefs.ts +src/models/B.ts +src/models/C.ts +src/models/OneOfInlineAndRefs.ts +src/models/OneOfInlineAndRefsOneOf.ts +src/models/OneOfInlineAndRefsOneOf1.ts +src/models/OneOfPrimitives.ts +src/models/OneOfPrimitivesAndRefs.ts +src/models/OneOfRefs.ts +src/models/Wrapper.ts +src/models/WrapperAllOf.ts +src/models/WrapperAnyOf.ts +src/models/WrapperOneOf.ts", "src/apis/DefaultApi.ts": "/* tslint:disable */ /* eslint-disable */ /** - * Data Types + * composite models * * * The version of the OpenAPI document: 1.0.0 @@ -1572,11 +1579,11 @@ src/models/DataTypes200Response.ts", import * as runtime from '../runtime'; import type { - DataTypes200Response, + Wrapper, } from '../models'; import { - DataTypes200ResponseFromJSON, - DataTypes200ResponseToJSON, + WrapperFromJSON, + WrapperToJSON, } from '../models'; @@ -1587,7 +1594,7 @@ export class DefaultApi extends runtime.BaseAPI { /** * */ - async dataTypesRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + async opGetRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const queryParameters: any = {}; @@ -1596,20 +1603,20 @@ export class DefaultApi extends runtime.BaseAPI { const response = await this.request({ - path: \`/types\`, + path: \`/op\`, method: 'GET', headers: headerParameters, query: queryParameters, }, initOverrides); - return new runtime.JSONApiResponse(response, (jsonValue) => DataTypes200ResponseFromJSON(jsonValue)); + return new runtime.JSONApiResponse(response, (jsonValue) => WrapperFromJSON(jsonValue)); } /** * */ - async dataTypes(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { - const response = await this.dataTypesRaw(initOverrides); + async opGet(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.opGetRaw(initOverrides); return await response.value(); } @@ -1618,9 +1625,75 @@ export class DefaultApi extends runtime.BaseAPI { ", "src/apis/DefaultApi/OperationConfig.ts": "// Import models import { - DataTypes200Response, - DataTypes200ResponseFromJSON, - DataTypes200ResponseToJSON, + A, + AFromJSON, + AToJSON, + AllOfInlineAndRefs, + AllOfInlineAndRefsFromJSON, + AllOfInlineAndRefsToJSON, + AllOfInlineAndRefsAllOf, + AllOfInlineAndRefsAllOfFromJSON, + AllOfInlineAndRefsAllOfToJSON, + AllOfInlineAndRefsAllOf1, + AllOfInlineAndRefsAllOf1FromJSON, + AllOfInlineAndRefsAllOf1ToJSON, + AllOfRefs, + AllOfRefsFromJSON, + AllOfRefsToJSON, + AnyOfInlineAndRefs, + AnyOfInlineAndRefsFromJSON, + AnyOfInlineAndRefsToJSON, + AnyOfInlineAndRefsAnyOf, + AnyOfInlineAndRefsAnyOfFromJSON, + AnyOfInlineAndRefsAnyOfToJSON, + AnyOfInlineAndRefsAnyOf1, + AnyOfInlineAndRefsAnyOf1FromJSON, + AnyOfInlineAndRefsAnyOf1ToJSON, + AnyOfPrimitives, + AnyOfPrimitivesFromJSON, + AnyOfPrimitivesToJSON, + AnyOfPrimitivesAndRefs, + AnyOfPrimitivesAndRefsFromJSON, + AnyOfPrimitivesAndRefsToJSON, + AnyOfRefs, + AnyOfRefsFromJSON, + AnyOfRefsToJSON, + B, + BFromJSON, + BToJSON, + C, + CFromJSON, + CToJSON, + OneOfInlineAndRefs, + OneOfInlineAndRefsFromJSON, + OneOfInlineAndRefsToJSON, + OneOfInlineAndRefsOneOf, + OneOfInlineAndRefsOneOfFromJSON, + OneOfInlineAndRefsOneOfToJSON, + OneOfInlineAndRefsOneOf1, + OneOfInlineAndRefsOneOf1FromJSON, + OneOfInlineAndRefsOneOf1ToJSON, + OneOfPrimitives, + OneOfPrimitivesFromJSON, + OneOfPrimitivesToJSON, + OneOfPrimitivesAndRefs, + OneOfPrimitivesAndRefsFromJSON, + OneOfPrimitivesAndRefsToJSON, + OneOfRefs, + OneOfRefsFromJSON, + OneOfRefsToJSON, + Wrapper, + WrapperFromJSON, + WrapperToJSON, + WrapperAllOf, + WrapperAllOfFromJSON, + WrapperAllOfToJSON, + WrapperAnyOf, + WrapperAnyOfFromJSON, + WrapperAnyOfToJSON, + WrapperOneOf, + WrapperOneOfFromJSON, + WrapperOneOfToJSON, } from '../../models'; // Import request parameter interfaces import { @@ -1631,13 +1704,13 @@ import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda // Generic type for object keyed by operation names export interface OperationConfig { - dataTypes: T; + opGet: T; } // Look up path and http method for a given operation name export const OperationLookup = { - dataTypes: { - path: '/types', + opGet: { + path: '/op', method: 'GET', contentTypes: ['application/json'], }, @@ -1757,7 +1830,7 @@ const extractResponseHeadersFromInterceptors = (interceptors: any[]): { [key: st }), {} as { [key: string]: string }); }; -export type OperationIds = | 'dataTypes'; +export type OperationIds = | 'opGet'; export type OperationApiGatewayProxyResult = APIGatewayProxyResult & { __operationId?: T }; // Api gateway lambda handler type @@ -1834,32 +1907,32 @@ const buildHandlerChain = ( }; /** - * Path, Query and Header parameters for DataTypes + * Path, Query and Header parameters for OpGet */ -export interface DataTypesRequestParameters { +export interface OpGetRequestParameters { } /** - * Request body parameter for DataTypes + * Request body parameter for OpGet */ -export type DataTypesRequestBody = never; +export type OpGetRequestBody = never; -export type DataTypes200OperationResponse = OperationResponse<200, DataTypes200Response>; +export type OpGet200OperationResponse = OperationResponse<200, Wrapper>; -export type DataTypesOperationResponses = | DataTypes200OperationResponse ; +export type OpGetOperationResponses = | OpGet200OperationResponse ; // Type that the handler function provided to the wrapper must conform to -export type DataTypesHandlerFunction = LambdaHandlerFunction; -export type DataTypesChainedHandlerFunction = ChainedLambdaHandlerFunction; -export type DataTypesChainedRequestInput = ChainedRequestInput; +export type OpGetHandlerFunction = LambdaHandlerFunction; +export type OpGetChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type OpGetChainedRequestInput = ChainedRequestInput; /** - * Lambda handler wrapper to provide typed interface for the implementation of dataTypes + * Lambda handler wrapper to provide typed interface for the implementation of opGet */ -export const dataTypesHandler = ( - ...handlers: [DataTypesChainedHandlerFunction, ...DataTypesChainedHandlerFunction[]] -): OperationApiGatewayLambdaHandler<'dataTypes'> => async (event: any, context: any, _callback?: any, additionalInterceptors: DataTypesChainedHandlerFunction[] = []): Promise => { - const operationId = "dataTypes"; +export const opGetHandler = ( + ...handlers: [OpGetChainedHandlerFunction, ...OpGetChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'opGet'> => async (event: any, context: any, _callback?: any, additionalInterceptors: OpGetChainedHandlerFunction[] = []): Promise => { + const operationId = "opGet"; const rawSingleValueParameters = decodeRequestParameters({ ...(event.pathParameters || {}), @@ -1875,7 +1948,7 @@ export const dataTypesHandler = ( let marshalledBody = responseBody; switch(statusCode) { case 200: - marshalledBody = JSON.stringify(DataTypes200ResponseToJSON(marshalledBody)); + marshalledBody = JSON.stringify(WrapperToJSON(marshalledBody)); break; default: break; @@ -1895,7 +1968,7 @@ export const dataTypesHandler = ( return headers; }; - let requestParameters: DataTypesRequestParameters | undefined = undefined; + let requestParameters: OpGetRequestParameters | undefined = undefined; try { requestParameters = { @@ -1920,7 +1993,7 @@ export const dataTypesHandler = ( const demarshal = (bodyString: string): any => { return {}; }; - const body = parseBody(event.body, demarshal, ['application/json']) as DataTypesRequestBody; + const body = parseBody(event.body, demarshal, ['application/json']) as OpGetRequestBody; const chain = buildHandlerChain(...additionalInterceptors, ...handlers); const response = await chain.next({ @@ -1944,12 +2017,12 @@ export const dataTypesHandler = ( }; export interface HandlerRouterHandlers { - readonly dataTypes: OperationApiGatewayLambdaHandler<'dataTypes'>; + readonly opGet: OperationApiGatewayLambdaHandler<'opGet'>; } -export type AnyOperationRequestParameters = | DataTypesRequestParameters; -export type AnyOperationRequestBodies = | DataTypesRequestBody; -export type AnyOperationResponses = | DataTypesOperationResponses; +export type AnyOperationRequestParameters = | OpGetRequestParameters; +export type AnyOperationRequestBodies = | OpGetRequestBody; +export type AnyOperationResponses = | OpGetOperationResponses; export interface HandlerRouterProps< RequestParameters, @@ -2275,26 +2348,3892 @@ export const buildTryCatchInterceptor = any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} +", + "src/response/response.ts": "import { OperationResponse } from '..'; + + +/** + * Helpers for constructing api responses + */ +export class Response { + /** + * A successful response + */ + public static success = ( + body: T + ): OperationResponse<200, T> => ({ + statusCode: 200, + body, + }); + + /** + * A response which indicates a client error + */ + public static badRequest = ( + body: T + ): OperationResponse<400, T> => ({ + statusCode: 400, + body, + }); + + /** + * A response which indicates the requested resource was not found + */ + public static notFound = ( + body: T + ): OperationResponse<404, T> => ({ + statusCode: 404, + body, + }); + + /** + * A response which indicates the caller is not authorised to perform the operation or access the resource + */ + public static notAuthorized = ( + body: T + ): OperationResponse<403, T> => ({ + statusCode: 403, + body, + }); + + /** + * A response to indicate a server error + */ + public static internalFailure = ( + body: T + ): OperationResponse<500, T> => ({ + statusCode: 500, + body, + }); +} +", + "src/runtime.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * composite models + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + +export const BASE_PATH = "http://localhost".replace(/\\/+$/, ""); + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | ((name: string) => string); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + set config(configuration: Configuration) { + this.configuration = configuration; + } + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export const DefaultConfig = new Configuration(); + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private middleware: Middleware[]; + + constructor(protected configuration = DefaultConfig) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); + const response = await this.fetchApi(url, init); + if (response && (response.status >= 200 && response.status < 300)) { + return response; + } + throw new ResponseError(response, 'Response returned an error code'); + } + + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + + const headers = Object.assign({}, this.configuration.headers, context.headers); + Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {}); + + const initOverrideFn = + typeof initOverrides === "function" + ? initOverrides + : async () => initOverrides; + + const initParams = { + method: context.method, + headers, + body: context.body, + credentials: this.configuration.credentials, + }; + + const overriddenInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + }; + + const init: RequestInit = { + ...overriddenInit, + body: + isFormData(overriddenInit.body) || + overriddenInit.body instanceof URLSearchParams || + isBlob(overriddenInit.body) + ? overriddenInit.body + : JSON.stringify(overriddenInit.body), + }; + + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response: Response | undefined = undefined; + try { + response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); + } catch (e) { + for (const middleware of this.middleware) { + if (middleware.onError) { + response = await middleware.onError({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + error: e, + response: response ? response.clone() : undefined, + }) || response; + } + } + if (response === undefined) { + if (e instanceof Error) { + throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } + } + } + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of \`this\` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +function isBlob(value: any): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob; +} + +function isFormData(value: any): value is FormData { + return typeof FormData !== "undefined" && value instanceof FormData; +} + +export class ResponseError extends Error { + override name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + } +} + +export class FetchError extends Error { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { + super(msg); + } +} + +export class RequiredError extends Error { + override name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map(key => querystringSingleKey(key, params[key], prefix)) + .filter(part => part.length > 0) + .join('&'); +} + +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + const fullKey = keyPrefix + (keyPrefix.length ? \`[\${key}]\` : key); + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(\`&\${encodeURIComponent(fullKey)}=\`); + return \`\${encodeURIComponent(fullKey)}=\${multiValue}\`; + } + if (value instanceof Set) { + const valueAsArray = Array.from(value); + return querystringSingleKey(key, valueAsArray, keyPrefix); + } + if (value instanceof Date) { + return \`\${encodeURIComponent(fullKey)}=\${encodeURIComponent(value.toISOString())}\`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return \`\${encodeURIComponent(fullKey)}=\${encodeURIComponent(String(value))}\`; +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string; +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface ErrorContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + error: unknown; + response?: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; + onError?(context: ErrorContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} +", +} +`; + +exports[`Typescript Client Code Generation Script Unit Tests Generates With data-types.yaml 1`] = ` +{ + ".tsapi-manifest": "src/index.ts +src/runtime.ts +src/interceptors/try-catch.ts +src/interceptors/cors.ts +src/interceptors/powertools/logger.ts +src/interceptors/powertools/tracer.ts +src/interceptors/powertools/metrics.ts +src/interceptors/index.ts +src/apis/DefaultApi/OperationConfig.ts +src/response/response.ts +src/apis/DefaultApi.ts +src/apis/index.ts +src/models/index.ts +src/models/model-utils.ts +src/models/DataTypes200Response.ts +src/models/DataTypes200ResponseMyAllOf.ts +src/models/DataTypes200ResponseMyAllOfAllOf.ts +src/models/DataTypes200ResponseMyAllOfAllOf1.ts +src/models/DataTypes200ResponseMyAnyOf.ts +src/models/DataTypes200ResponseMyNotNot.ts +src/models/DataTypes200ResponseMyObject.ts +src/models/DataTypes200ResponseMyObjectOne.ts +src/models/DataTypes200ResponseMyObjectOneTwo.ts +src/models/DataTypes200ResponseMyOneOf.ts", + "src/apis/DefaultApi.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import type { + DataTypes200Response, +} from '../models'; +import { + DataTypes200ResponseFromJSON, + DataTypes200ResponseToJSON, +} from '../models'; + + +/** + * + */ +export class DefaultApi extends runtime.BaseAPI { + /** + * + */ + async dataTypesRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + + const headerParameters: runtime.HTTPHeaders = {}; + + + + const response = await this.request({ + path: \`/types\`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DataTypes200ResponseFromJSON(jsonValue)); + } + + /** + * + */ + async dataTypes(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.dataTypesRaw(initOverrides); + return await response.value(); + } + +} + +", + "src/apis/DefaultApi/OperationConfig.ts": "// Import models +import { + DataTypes200Response, + DataTypes200ResponseFromJSON, + DataTypes200ResponseToJSON, + DataTypes200ResponseMyAllOf, + DataTypes200ResponseMyAllOfFromJSON, + DataTypes200ResponseMyAllOfToJSON, + DataTypes200ResponseMyAllOfAllOf, + DataTypes200ResponseMyAllOfAllOfFromJSON, + DataTypes200ResponseMyAllOfAllOfToJSON, + DataTypes200ResponseMyAllOfAllOf1, + DataTypes200ResponseMyAllOfAllOf1FromJSON, + DataTypes200ResponseMyAllOfAllOf1ToJSON, + DataTypes200ResponseMyAnyOf, + DataTypes200ResponseMyAnyOfFromJSON, + DataTypes200ResponseMyAnyOfToJSON, + DataTypes200ResponseMyNotNot, + DataTypes200ResponseMyNotNotFromJSON, + DataTypes200ResponseMyNotNotToJSON, + DataTypes200ResponseMyObject, + DataTypes200ResponseMyObjectFromJSON, + DataTypes200ResponseMyObjectToJSON, + DataTypes200ResponseMyObjectOne, + DataTypes200ResponseMyObjectOneFromJSON, + DataTypes200ResponseMyObjectOneToJSON, + DataTypes200ResponseMyObjectOneTwo, + DataTypes200ResponseMyObjectOneTwoFromJSON, + DataTypes200ResponseMyObjectOneTwoToJSON, + DataTypes200ResponseMyOneOf, + DataTypes200ResponseMyOneOfFromJSON, + DataTypes200ResponseMyOneOfToJSON, +} from '../../models'; +// Import request parameter interfaces +import { +} from '..'; + +// API Gateway Types +import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda"; + +// Generic type for object keyed by operation names +export interface OperationConfig { + dataTypes: T; +} + +// Look up path and http method for a given operation name +export const OperationLookup = { + dataTypes: { + path: '/types', + method: 'GET', + contentTypes: ['application/json'], + }, +}; + +export class Operations { + /** + * Return an OperationConfig with the same value for every operation + */ + public static all = (value: T): OperationConfig => Object.fromEntries( + Object.keys(OperationLookup).map((operationId) => [operationId, value]) + ) as unknown as OperationConfig; +} + +// Standard apigateway request parameters (query parameters or path parameters, multi or single value) +type ApiGatewayRequestParameters = { [key: string]: string | string[] | undefined }; + +/** + * URI decode for a string or array of strings + */ +const uriDecode = (value: string | string[]): string | string[] => + typeof value === 'string' ? decodeURIComponent(value) : value.map((v) => decodeURIComponent(v)); + +/** + * URI decodes apigateway request parameters (query or path parameters) + */ +const decodeRequestParameters = (parameters: ApiGatewayRequestParameters): ApiGatewayRequestParameters => { + const decodedParameters = {}; + Object.keys(parameters || {}).forEach((key) => { + decodedParameters[key] = parameters[key] ? uriDecode(parameters[key]) : parameters[key]; + }); + return decodedParameters; +}; + +/** + * Parse the body if the content type is json, otherwise leave as a raw string + */ +const parseBody = (body: string, demarshal: (body: string) => any, contentTypes: string[]): any => contentTypes.filter((contentType) => contentType !== 'application/json').length === 0 ? demarshal(body || '{}') : body; + +const assertRequired = (required: boolean, baseName: string, parameters: any) => { + if(required && parameters[baseName] === undefined) { + throw new Error(\`Missing required request parameter '\${baseName}'\`); + } +}; + +const coerceNumber = (baseName: string, s: string, isInteger: boolean): number => { + const n = Number(s); + if (isNaN(n)) { + throw new Error(\`Expected a number for request parameter '\${baseName}'\`); + } + if (isInteger && !Number.isInteger(n)) { + throw new Error(\`Expected an integer for request parameter '\${baseName}'\`); + } + return n; +}; + +const coerceBoolean = (baseName: string, s: string): boolean => { + switch (s) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(\`Expected a boolean (true or false) for request parameter '\${baseName}'\`); + } +}; + +const coerceDate = (baseName: string, s: string): Date => { + const d = new Date(s); + if (isNaN(d as any)) { + throw new Error(\`Expected a valid date (iso format) for request parameter '\${baseName}'\`); + } + return d; +}; + +const coerceParameter = ( + baseName: string, + dataType: string, + isInteger: boolean, + rawStringParameters: { [key: string]: string | undefined }, + rawStringArrayParameters: { [key: string]: string[] | undefined }, + required: boolean, +) => { + switch (dataType) { + case "number": + assertRequired(required, baseName, rawStringParameters); + return rawStringParameters[baseName] !== undefined ? coerceNumber(baseName, rawStringParameters[baseName], isInteger) : undefined; + case "boolean": + assertRequired(required, baseName, rawStringParameters); + return rawStringParameters[baseName] !== undefined ? coerceBoolean(baseName, rawStringParameters[baseName]) : undefined; + case "Date": + assertRequired(required, baseName, rawStringParameters); + return rawStringParameters[baseName] !== undefined ? coerceDate(baseName, rawStringParameters[baseName]) : undefined; + case "Array": + assertRequired(required, baseName, rawStringArrayParameters); + return rawStringArrayParameters[baseName] !== undefined ? rawStringArrayParameters[baseName].map(n => coerceNumber(baseName, n, isInteger)) : undefined; + case "Array": + assertRequired(required, baseName, rawStringArrayParameters); + return rawStringArrayParameters[baseName] !== undefined ? rawStringArrayParameters[baseName].map(n => coerceBoolean(baseName, n)) : undefined; + case "Array": + assertRequired(required, baseName, rawStringArrayParameters); + return rawStringArrayParameters[baseName] !== undefined ? rawStringArrayParameters[baseName].map(n => coerceDate(baseName, n)) : undefined; + case "Array": + assertRequired(required, baseName, rawStringArrayParameters); + return rawStringArrayParameters[baseName]; + case "string": + default: + assertRequired(required, baseName, rawStringParameters); + return rawStringParameters[baseName]; + } +}; + +const extractResponseHeadersFromInterceptors = (interceptors: any[]): { [key: string]: string } => { + return (interceptors ?? []).reduce((interceptor: any, headers: { [key: string]: string }) => ({ + ...headers, + ...(interceptor?.__type_safe_api_response_headers ?? {}), + }), {} as { [key: string]: string }); +}; + +export type OperationIds = | 'dataTypes'; +export type OperationApiGatewayProxyResult = APIGatewayProxyResult & { __operationId?: T }; + +// Api gateway lambda handler type +export type OperationApiGatewayLambdaHandler = (event: APIGatewayProxyEvent, context: Context) => Promise>; + +// Type of the response to be returned by an operation lambda handler +export interface OperationResponse { + statusCode: StatusCode; + headers?: { [key: string]: string }; + multiValueHeaders?: { [key: string]: string[] }; + body: Body; +} + +// Input for a lambda handler for an operation +export type LambdaRequestParameters = { + requestParameters: RequestParameters, + body: RequestBody, +}; + +export type InterceptorContext = { [key: string]: any }; + +export interface RequestInput { + input: LambdaRequestParameters; + event: APIGatewayProxyEvent; + context: Context; + interceptorContext: InterceptorContext; +} + +export interface ChainedRequestInput extends RequestInput { + chain: LambdaHandlerChain; +} + +/** + * A lambda handler function which is part of a chain. It may invoke the remainder of the chain via the given chain input + */ +export type ChainedLambdaHandlerFunction = ( + input: ChainedRequestInput, +) => Promise; + +// Type for a lambda handler function to be wrapped +export type LambdaHandlerFunction = ( + input: RequestInput, +) => Promise; + +export interface LambdaHandlerChain { + next: LambdaHandlerFunction; +} + +// Interceptor is a type alias for ChainedLambdaHandlerFunction +export type Interceptor = ChainedLambdaHandlerFunction; + +/** + * Build a chain from the given array of chained lambda handlers + */ +const buildHandlerChain = ( + ...handlers: ChainedLambdaHandlerFunction[] +): LambdaHandlerChain => { + if (handlers.length === 0) { + return { + next: () => { + throw new Error("No more handlers remain in the chain! The last handler should not call next."); + } + }; + } + const [currentHandler, ...remainingHandlers] = handlers; + return { + next: (input) => { + return currentHandler({ + ...input, + chain: buildHandlerChain(...remainingHandlers), + }); + }, + }; +}; + +/** + * Path, Query and Header parameters for DataTypes + */ +export interface DataTypesRequestParameters { +} + +/** + * Request body parameter for DataTypes + */ +export type DataTypesRequestBody = never; + +export type DataTypes200OperationResponse = OperationResponse<200, DataTypes200Response>; + +export type DataTypesOperationResponses = | DataTypes200OperationResponse ; + +// Type that the handler function provided to the wrapper must conform to +export type DataTypesHandlerFunction = LambdaHandlerFunction; +export type DataTypesChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type DataTypesChainedRequestInput = ChainedRequestInput; + +/** + * Lambda handler wrapper to provide typed interface for the implementation of dataTypes + */ +export const dataTypesHandler = ( + ...handlers: [DataTypesChainedHandlerFunction, ...DataTypesChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'dataTypes'> => async (event: any, context: any, _callback?: any, additionalInterceptors: DataTypesChainedHandlerFunction[] = []): Promise => { + const operationId = "dataTypes"; + + 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(DataTypes200ResponseToJSON(marshalledBody)); + break; + default: + break; + } + + return marshalledBody; + }; + + const errorHeaders = (statusCode: number): { [key: string]: string } => { + let headers = {}; + + switch(statusCode) { + default: + break; + } + + return headers; + }; + + let requestParameters: DataTypesRequestParameters | 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 DataTypesRequestBody; + + 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 dataTypes: OperationApiGatewayLambdaHandler<'dataTypes'>; +} + +export type AnyOperationRequestParameters = | DataTypesRequestParameters; +export type AnyOperationRequestBodies = | DataTypesRequestBody; +export type AnyOperationResponses = | DataTypesOperationResponses; + +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 + */ + readonly handlers: HandlerRouterHandlers; +} + +const concatMethodAndPath = (method: string, path: string) => \`\${method.toLowerCase()}||\${path}\`; + +const OperationIdByMethodAndPath = Object.fromEntries(Object.entries(OperationLookup).map( + ([operationId, methodAndPath]) => [concatMethodAndPath(methodAndPath.method, methodAndPath.path), operationId] +)); + +/** + * Returns a lambda handler which can be used to route requests to the appropriate typed lambda handler function. + */ +export const handlerRouter = (props: HandlerRouterProps< + AnyOperationRequestParameters, + AnyOperationRequestBodies, + AnyOperationResponses +>): OperationApiGatewayLambdaHandler => async (event, context) => { + const operationId = OperationIdByMethodAndPath[concatMethodAndPath(event.requestContext.httpMethod, event.requestContext.resourcePath)]; + const handler = props.handlers[operationId]; + return handler(event, context, undefined, props.interceptors); +}; +", + "src/apis/index.ts": "/* tslint:disable */ +/* eslint-disable */ +export * from './DefaultApi'; +", + "src/index.ts": "/* tslint:disable */ +/* eslint-disable */ +export * from './runtime'; +export * from './apis'; +export * from './models'; +export * from './apis/DefaultApi/OperationConfig'; +export * from './response/response'; +export * from './interceptors' +", + "src/interceptors/cors.ts": "import { ChainedRequestInput, OperationResponse } from '..'; + +// By default, allow all origins and headers +const DEFAULT_CORS_HEADERS: { [key: string]: string } = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Headers': '*', +}; + +/** + * Create an interceptor for adding headers to the response + * @param additionalHeaders headers to add to the response + */ +export const buildResponseHeaderInterceptor = (additionalHeaders: { [key: string]: string }) => { + const interceptor = async < + RequestParameters, + RequestBody, + Response extends OperationResponse + >( + request: ChainedRequestInput, + ): Promise => { + const result = await request.chain.next(request); + return { + ...result, + headers: { + ...additionalHeaders, + ...result.headers, + }, + }; + }; + + // Any error responses returned during request validation will include the headers + (interceptor as any).__type_safe_api_response_headers = additionalHeaders; + + return interceptor; +}; + +/** + * An interceptor for adding cross-origin resource sharing (CORS) headers to the response. + * Allows all origins and headers. Use buildResponseHeaderInterceptor to customise. + */ +export const corsInterceptor = buildResponseHeaderInterceptor(DEFAULT_CORS_HEADERS); +", + "src/interceptors/index.ts": "import { corsInterceptor } from './cors'; +import { LoggingInterceptor } from './powertools/logger'; +import { MetricsInterceptor } from './powertools/metrics'; +import { TracingInterceptor } from './powertools/tracer'; +import { tryCatchInterceptor } from './try-catch'; + +export * from './cors'; +export * from './try-catch'; +export * from './powertools/tracer'; +export * from './powertools/metrics'; +export * from './powertools/logger'; + +/** + * All default interceptors, for logging, tracing, metrics, cors headers and error handling + */ +export const INTERCEPTORS = [ + corsInterceptor, + LoggingInterceptor.intercept, + tryCatchInterceptor, + TracingInterceptor.intercept, + MetricsInterceptor.intercept, +] as const; +", + "src/interceptors/powertools/logger.ts": "import { Logger } from '@aws-lambda-powertools/logger'; +import { ChainedRequestInput, OperationResponse } from '../..'; + +const logger = new Logger(); + +export class LoggingInterceptor { + /** + * Interceptor which adds an aws lambda powertools logger to the interceptor context, + * and adds the lambda context + * @see https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/ + */ + public static intercept = async < + RequestParameters, + RequestArrayParameters, + RequestBody, + Response extends OperationResponse + >( + request: ChainedRequestInput, + ): Promise => { + logger.addContext(request.context); + logger.appendKeys({ operationId: request.interceptorContext.operationId }); + request.interceptorContext.logger = logger; + const response = await request.chain.next(request); + logger.removeKeys(['operationId']); + return response; + }; + + /** + * Retrieve the logger from the interceptor context + */ + public static getLogger = < + RequestParameters, + RequestArrayParameters, + RequestBody, + Response extends OperationResponse + >(request: ChainedRequestInput): Logger => { + if (!request.interceptorContext.logger) { + throw new Error('No logger found, did you configure the LoggingInterceptor?'); + } + return request.interceptorContext.logger; + }; +} +", + "src/interceptors/powertools/metrics.ts": "import { Metrics } from '@aws-lambda-powertools/metrics'; +import { ChainedRequestInput, OperationResponse } from '../..'; + +const metrics = new Metrics(); + +export class MetricsInterceptor { + /** + * Interceptor which adds an instance of aws lambda powertools metrics to the interceptor context, + * and ensures metrics are flushed prior to finishing the lambda execution + * @see https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics/ + */ + public static intercept = async < + RequestParameters, + RequestArrayParameters, + RequestBody, + Response extends OperationResponse + >( + request: ChainedRequestInput, + ): Promise => { + metrics.addDimension("operationId", request.interceptorContext.operationId); + request.interceptorContext.metrics = metrics; + try { + return await request.chain.next(request); + } finally { + // Flush metrics + metrics.publishStoredMetrics(); + } + }; + + /** + * Retrieve the metrics logger from the request + */ + public static getMetrics = < + RequestParameters, + RequestArrayParameters, + RequestBody, + Response extends OperationResponse + >( + request: ChainedRequestInput, + ): Metrics => { + if (!request.interceptorContext.metrics) { + throw new Error('No metrics logger found, did you configure the MetricsInterceptor?'); + } + return request.interceptorContext.metrics; + }; +} +", + "src/interceptors/powertools/tracer.ts": "import { Tracer } from '@aws-lambda-powertools/tracer'; +import { ChainedRequestInput, OperationResponse } from '../..'; + +const tracer = new Tracer(); + +export interface TracingInterceptorOptions { + /** + * Whether to add the response as metadata to the trace + */ + readonly addResponseAsMetadata?: boolean; +} + +/** + * Create an 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/typescript/latest/core/tracer/#lambda-handler + */ +export const buildTracingInterceptor = (options?: TracingInterceptorOptions) => async < + RequestParameters, + RequestBody, + Response extends OperationResponse +>( + request: ChainedRequestInput, +): Promise => { + const handler = request.interceptorContext.operationId ?? process.env._HANDLER ?? 'index.handler'; + const segment = tracer.getSegment(); + let subsegment; + if (segment) { + subsegment = segment.addNewSubsegment(handler); + tracer.setSegment(subsegment); + } + + tracer.annotateColdStart(); + tracer.addServiceNameAnnotation(); + + if (request.interceptorContext.logger) { + tracer.provider.setLogger(request.interceptorContext.logger); + } + + request.interceptorContext.tracer = tracer; + + try { + const result = await request.chain.next(request); + if (options?.addResponseAsMetadata) { + tracer.addResponseAsMetadata(result, handler); + } + return result; + } catch (e) { + tracer.addErrorAsMetadata(e as Error); + throw e; + } finally { + if (segment && subsegment) { + subsegment.close(); + tracer.setSegment(segment); + } + } +}; + +export class TracingInterceptor { + /** + * 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. + */ + public static intercept = buildTracingInterceptor(); + + /** + * Get the tracer from the interceptor context + */ + public static getTracer = < + RequestParameters, + RequestArrayParameters, + RequestBody, + Response extends OperationResponse + >( + request: ChainedRequestInput, + ): Tracer => { + if (!request.interceptorContext.tracer) { + throw new Error('No tracer found, did you configure the TracingInterceptor?'); + } + return request.interceptorContext.tracer; + }; +} +", + "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/DataTypes200Response.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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 { DataTypes200ResponseMyAllOf } from './DataTypes200ResponseMyAllOf'; +import { + DataTypes200ResponseMyAllOfFromJSON, + DataTypes200ResponseMyAllOfFromJSONTyped, + DataTypes200ResponseMyAllOfToJSON, + instanceOfDataTypes200ResponseMyAllOf, +} from './DataTypes200ResponseMyAllOf'; +import type { DataTypes200ResponseMyAnyOf } from './DataTypes200ResponseMyAnyOf'; +import { + DataTypes200ResponseMyAnyOfFromJSON, + DataTypes200ResponseMyAnyOfFromJSONTyped, + DataTypes200ResponseMyAnyOfToJSON, + instanceOfDataTypes200ResponseMyAnyOf, +} from './DataTypes200ResponseMyAnyOf'; +import type { DataTypes200ResponseMyObject } from './DataTypes200ResponseMyObject'; +import { + DataTypes200ResponseMyObjectFromJSON, + DataTypes200ResponseMyObjectFromJSONTyped, + DataTypes200ResponseMyObjectToJSON, + instanceOfDataTypes200ResponseMyObject, +} from './DataTypes200ResponseMyObject'; +import type { DataTypes200ResponseMyOneOf } from './DataTypes200ResponseMyOneOf'; +import { + DataTypes200ResponseMyOneOfFromJSON, + DataTypes200ResponseMyOneOfFromJSONTyped, + DataTypes200ResponseMyOneOfToJSON, + instanceOfDataTypes200ResponseMyOneOf, +} from './DataTypes200ResponseMyOneOf'; + +/** + * + * @export + * @interface DataTypes200Response + */ +export interface DataTypes200Response { + /** + * + * @type {number} + * @memberof DataTypes200Response + */ + myInt?: number; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myString?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myStringLength?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myLongMinStringLength?: string; + /** + * + * @type {boolean} + * @memberof DataTypes200Response + */ + myBool?: boolean; + /** + * + * @type {number} + * @memberof DataTypes200Response + */ + myNumber?: number; + /** + * + * @type {Array} + * @memberof DataTypes200Response + */ + myDateArray?: Array; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myEmail?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myUrl?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myHostname?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myIpv4?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myIpv6?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myUuid?: string; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myByte?: string; + /** + * + * @type {Date} + * @memberof DataTypes200Response + */ + myDateTime?: Date; + /** + * + * @type {string} + * @memberof DataTypes200Response + */ + myRegexPattern?: string; + /** + * + * @type {DataTypes200ResponseMyOneOf} + * @memberof DataTypes200Response + */ + myOneOf?: DataTypes200ResponseMyOneOf; + /** + * + * @type {DataTypes200ResponseMyAnyOf} + * @memberof DataTypes200Response + */ + myAnyOf?: DataTypes200ResponseMyAnyOf; + /** + * + * @type {DataTypes200ResponseMyAllOf} + * @memberof DataTypes200Response + */ + myAllOf?: DataTypes200ResponseMyAllOf; + /** + * + * @type {any} + * @memberof DataTypes200Response + */ + myNot?: any | null; + /** + * + * @type {any} + * @memberof DataTypes200Response + */ + myNotString?: any | null; + /** + * + * @type {{ [key: string]: Array; }} + * @memberof DataTypes200Response + */ + myAdditionalProperties?: { [key: string]: Array; }; + /** + * + * @type {DataTypes200ResponseMyObject} + * @memberof DataTypes200Response + */ + myObject?: DataTypes200ResponseMyObject; +} + + +/** + * Check if a given object implements the DataTypes200Response interface. + */ +export function instanceOfDataTypes200Response(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DataTypes200ResponseFromJSON(json: any): DataTypes200Response { + return DataTypes200ResponseFromJSONTyped(json, false); +} + +export function DataTypes200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200Response { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'myInt': !exists(json, 'myInt') ? undefined : json['myInt'], + 'myString': !exists(json, 'myString') ? undefined : json['myString'], + 'myStringLength': !exists(json, 'myStringLength') ? undefined : json['myStringLength'], + 'myLongMinStringLength': !exists(json, 'myLongMinStringLength') ? undefined : json['myLongMinStringLength'], + 'myBool': !exists(json, 'myBool') ? undefined : json['myBool'], + 'myNumber': !exists(json, 'myNumber') ? undefined : json['myNumber'], + 'myDateArray': !exists(json, 'myDateArray') ? undefined : json['myDateArray'], + 'myEmail': !exists(json, 'myEmail') ? undefined : json['myEmail'], + 'myUrl': !exists(json, 'myUrl') ? undefined : json['myUrl'], + 'myHostname': !exists(json, 'myHostname') ? undefined : json['myHostname'], + 'myIpv4': !exists(json, 'myIpv4') ? undefined : json['myIpv4'], + 'myIpv6': !exists(json, 'myIpv6') ? undefined : json['myIpv6'], + 'myUuid': !exists(json, 'myUuid') ? undefined : json['myUuid'], + 'myByte': !exists(json, 'myByte') ? undefined : json['myByte'], + 'myDateTime': !exists(json, 'myDateTime') ? undefined : (new Date(json['myDateTime'])), + 'myRegexPattern': !exists(json, 'myRegexPattern') ? undefined : json['myRegexPattern'], + 'myOneOf': !exists(json, 'myOneOf') ? undefined : DataTypes200ResponseMyOneOfFromJSON(json['myOneOf']), + 'myAnyOf': !exists(json, 'myAnyOf') ? undefined : DataTypes200ResponseMyAnyOfFromJSON(json['myAnyOf']), + 'myAllOf': !exists(json, 'myAllOf') ? undefined : DataTypes200ResponseMyAllOfFromJSON(json['myAllOf']), + 'myNot': !exists(json, 'myNot') ? undefined : json['myNot'], + 'myNotString': !exists(json, 'myNotString') ? undefined : json['myNotString'], + 'myAdditionalProperties': !exists(json, 'myAdditionalProperties') ? undefined : json['myAdditionalProperties'], + 'myObject': !exists(json, 'myObject') ? undefined : DataTypes200ResponseMyObjectFromJSON(json['myObject']), + }; +} + +export function DataTypes200ResponseToJSON(value?: DataTypes200Response | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'myInt': value.myInt, + 'myString': value.myString, + 'myStringLength': value.myStringLength, + 'myLongMinStringLength': value.myLongMinStringLength, + 'myBool': value.myBool, + 'myNumber': value.myNumber, + 'myDateArray': value.myDateArray, + 'myEmail': value.myEmail, + 'myUrl': value.myUrl, + 'myHostname': value.myHostname, + 'myIpv4': value.myIpv4, + 'myIpv6': value.myIpv6, + 'myUuid': value.myUuid, + 'myByte': value.myByte, + 'myDateTime': value.myDateTime === undefined ? undefined : (value.myDateTime.toISOString()), + 'myRegexPattern': value.myRegexPattern, + 'myOneOf': DataTypes200ResponseMyOneOfToJSON(value.myOneOf), + 'myAnyOf': DataTypes200ResponseMyAnyOfToJSON(value.myAnyOf), + 'myAllOf': DataTypes200ResponseMyAllOfToJSON(value.myAllOf), + 'myNot': value.myNot, + 'myNotString': value.myNotString, + 'myAdditionalProperties': value.myAdditionalProperties, + 'myObject': DataTypes200ResponseMyObjectToJSON(value.myObject), + }; +} + +", + "src/models/DataTypes200ResponseMyAllOf.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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 { DataTypes200ResponseMyAllOfAllOf } from './DataTypes200ResponseMyAllOfAllOf'; +import { + DataTypes200ResponseMyAllOfAllOfFromJSON, + DataTypes200ResponseMyAllOfAllOfFromJSONTyped, + DataTypes200ResponseMyAllOfAllOfToJSON, + instanceOfDataTypes200ResponseMyAllOfAllOf, +} from './DataTypes200ResponseMyAllOfAllOf'; +import type { DataTypes200ResponseMyAllOfAllOf1 } from './DataTypes200ResponseMyAllOfAllOf1'; +import { + DataTypes200ResponseMyAllOfAllOf1FromJSON, + DataTypes200ResponseMyAllOfAllOf1FromJSONTyped, + DataTypes200ResponseMyAllOfAllOf1ToJSON, + instanceOfDataTypes200ResponseMyAllOfAllOf1, +} from './DataTypes200ResponseMyAllOfAllOf1'; + +/** + * @type DataTypes200ResponseMyAllOf + * + * @export + */ +export type DataTypes200ResponseMyAllOf = DataTypes200ResponseMyAllOfAllOf & DataTypes200ResponseMyAllOfAllOf1; + + +/** + * Check if a given object implements the DataTypes200ResponseMyAllOf interface. + */ +export function instanceOfDataTypes200ResponseMyAllOf(value: object): boolean { + return instanceOfDataTypes200ResponseMyAllOfAllOf(value) && instanceOfDataTypes200ResponseMyAllOfAllOf1(value) +} + +export function DataTypes200ResponseMyAllOfFromJSON(json: any): DataTypes200ResponseMyAllOf { + return DataTypes200ResponseMyAllOfFromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyAllOfFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyAllOf { + if ((json === undefined) || (json === null)) { + return json; + } + return { + ...DataTypes200ResponseMyAllOfAllOfFromJSONTyped(json, true), + ...DataTypes200ResponseMyAllOfAllOf1FromJSONTyped(json, true), + }; +} + +export function DataTypes200ResponseMyAllOfToJSON(value?: DataTypes200ResponseMyAllOf | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + ...DataTypes200ResponseMyAllOfAllOfToJSON(value as any), + ...DataTypes200ResponseMyAllOfAllOf1ToJSON(value as any), + }; +} + +", + "src/models/DataTypes200ResponseMyAllOfAllOf.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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 DataTypes200ResponseMyAllOfAllOf + */ +export interface DataTypes200ResponseMyAllOfAllOf { + /** + * + * @type {string} + * @memberof DataTypes200ResponseMyAllOfAllOf + */ + first?: string; +} + + +/** + * Check if a given object implements the DataTypes200ResponseMyAllOfAllOf interface. + */ +export function instanceOfDataTypes200ResponseMyAllOfAllOf(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DataTypes200ResponseMyAllOfAllOfFromJSON(json: any): DataTypes200ResponseMyAllOfAllOf { + return DataTypes200ResponseMyAllOfAllOfFromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyAllOfAllOfFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyAllOfAllOf { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'first': !exists(json, 'first') ? undefined : json['first'], + }; +} + +export function DataTypes200ResponseMyAllOfAllOfToJSON(value?: DataTypes200ResponseMyAllOfAllOf | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'first': value.first, + }; +} + +", + "src/models/DataTypes200ResponseMyAllOfAllOf1.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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 DataTypes200ResponseMyAllOfAllOf1 + */ +export interface DataTypes200ResponseMyAllOfAllOf1 { + /** + * + * @type {string} + * @memberof DataTypes200ResponseMyAllOfAllOf1 + */ + second?: string; +} + + +/** + * Check if a given object implements the DataTypes200ResponseMyAllOfAllOf1 interface. + */ +export function instanceOfDataTypes200ResponseMyAllOfAllOf1(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DataTypes200ResponseMyAllOfAllOf1FromJSON(json: any): DataTypes200ResponseMyAllOfAllOf1 { + return DataTypes200ResponseMyAllOfAllOf1FromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyAllOfAllOf1FromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyAllOfAllOf1 { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'second': !exists(json, 'second') ? undefined : json['second'], + }; +} + +export function DataTypes200ResponseMyAllOfAllOf1ToJSON(value?: DataTypes200ResponseMyAllOfAllOf1 | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'second': value.second, + }; +} + +", + "src/models/DataTypes200ResponseMyAnyOf.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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'; + +/** + * @type DataTypes200ResponseMyAnyOf + * + * @export + */ +export type DataTypes200ResponseMyAnyOf = string | number; + + +/** + * Check if a given object implements the DataTypes200ResponseMyAnyOf interface. + */ +export function instanceOfDataTypes200ResponseMyAnyOf(value: object): boolean { + return typeof value === "string" || typeof value === "number" +} + +export function DataTypes200ResponseMyAnyOfFromJSON(json: any): DataTypes200ResponseMyAnyOf { + return DataTypes200ResponseMyAnyOfFromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyAnyOfFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyAnyOf { + if ((json === undefined) || (json === null)) { + return json; + } + if (typeof json === "string") { + return json; + } + if (typeof json === "number") { + return json; + } + return json; +} + +export function DataTypes200ResponseMyAnyOfToJSON(value?: DataTypes200ResponseMyAnyOf | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + if (typeof value === "string") { + return value; + } + if (typeof value === "number") { + return value; + } + return value; +} + +", + "src/models/DataTypes200ResponseMyNotNot.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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 DataTypes200ResponseMyNotNot + */ +export interface DataTypes200ResponseMyNotNot { + /** + * + * @type {string} + * @memberof DataTypes200ResponseMyNotNot + */ + foo?: string; +} + + +/** + * Check if a given object implements the DataTypes200ResponseMyNotNot interface. + */ +export function instanceOfDataTypes200ResponseMyNotNot(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DataTypes200ResponseMyNotNotFromJSON(json: any): DataTypes200ResponseMyNotNot { + return DataTypes200ResponseMyNotNotFromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyNotNotFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyNotNot { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'foo': !exists(json, 'foo') ? undefined : json['foo'], + }; +} + +export function DataTypes200ResponseMyNotNotToJSON(value?: DataTypes200ResponseMyNotNot | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'foo': value.foo, + }; +} + +", + "src/models/DataTypes200ResponseMyObject.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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 { DataTypes200ResponseMyObjectOne } from './DataTypes200ResponseMyObjectOne'; +import { + DataTypes200ResponseMyObjectOneFromJSON, + DataTypes200ResponseMyObjectOneFromJSONTyped, + DataTypes200ResponseMyObjectOneToJSON, + instanceOfDataTypes200ResponseMyObjectOne, +} from './DataTypes200ResponseMyObjectOne'; + +/** + * + * @export + * @interface DataTypes200ResponseMyObject + */ +export interface DataTypes200ResponseMyObject { + /** + * + * @type {DataTypes200ResponseMyObjectOne} + * @memberof DataTypes200ResponseMyObject + */ + one?: DataTypes200ResponseMyObjectOne; + /** + * + * @type {string} + * @memberof DataTypes200ResponseMyObject + */ + oneString?: string; +} + + +/** + * Check if a given object implements the DataTypes200ResponseMyObject interface. + */ +export function instanceOfDataTypes200ResponseMyObject(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DataTypes200ResponseMyObjectFromJSON(json: any): DataTypes200ResponseMyObject { + return DataTypes200ResponseMyObjectFromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyObjectFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyObject { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'one': !exists(json, 'one') ? undefined : DataTypes200ResponseMyObjectOneFromJSON(json['one']), + 'oneString': !exists(json, 'oneString') ? undefined : json['oneString'], + }; +} + +export function DataTypes200ResponseMyObjectToJSON(value?: DataTypes200ResponseMyObject | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'one': DataTypes200ResponseMyObjectOneToJSON(value.one), + 'oneString': value.oneString, + }; +} + +", + "src/models/DataTypes200ResponseMyObjectOne.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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 { DataTypes200ResponseMyObjectOneTwo } from './DataTypes200ResponseMyObjectOneTwo'; +import { + DataTypes200ResponseMyObjectOneTwoFromJSON, + DataTypes200ResponseMyObjectOneTwoFromJSONTyped, + DataTypes200ResponseMyObjectOneTwoToJSON, + instanceOfDataTypes200ResponseMyObjectOneTwo, +} from './DataTypes200ResponseMyObjectOneTwo'; + +/** + * + * @export + * @interface DataTypes200ResponseMyObjectOne + */ +export interface DataTypes200ResponseMyObjectOne { + /** + * + * @type {string} + * @memberof DataTypes200ResponseMyObjectOne + */ + twoString?: string; + /** + * + * @type {DataTypes200ResponseMyObjectOneTwo} + * @memberof DataTypes200ResponseMyObjectOne + */ + two?: DataTypes200ResponseMyObjectOneTwo; +} + + +/** + * Check if a given object implements the DataTypes200ResponseMyObjectOne interface. + */ +export function instanceOfDataTypes200ResponseMyObjectOne(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DataTypes200ResponseMyObjectOneFromJSON(json: any): DataTypes200ResponseMyObjectOne { + return DataTypes200ResponseMyObjectOneFromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyObjectOneFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyObjectOne { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'twoString': !exists(json, 'twoString') ? undefined : json['twoString'], + 'two': !exists(json, 'two') ? undefined : DataTypes200ResponseMyObjectOneTwoFromJSON(json['two']), + }; +} + +export function DataTypes200ResponseMyObjectOneToJSON(value?: DataTypes200ResponseMyObjectOne | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; } + return { - // Return the default error message - return { statusCode, body: errorResponseBody }; - } -}; + 'twoString': value.twoString, + 'two': DataTypes200ResponseMyObjectOneTwoToJSON(value.two), + }; +} -/** - * 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/DataTypes200Response.ts": "/* tslint:disable */ + "src/models/DataTypes200ResponseMyObjectOneTwo.ts": "/* tslint:disable */ /* eslint-disable */ /** * Data Types @@ -2311,189 +6250,41 @@ import { exists, mapValues } from './model-utils'; /** * * @export - * @interface DataTypes200Response + * @interface DataTypes200ResponseMyObjectOneTwo */ -export interface DataTypes200Response { - /** - * - * @type {number} - * @memberof DataTypes200Response - */ - myInt?: number; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myString?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myStringLength?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myLongMinStringLength?: string; - /** - * - * @type {boolean} - * @memberof DataTypes200Response - */ - myBool?: boolean; - /** - * - * @type {number} - * @memberof DataTypes200Response - */ - myNumber?: number; - /** - * - * @type {Array} - * @memberof DataTypes200Response - */ - myDateArray?: Array; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myEmail?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myUrl?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myHostname?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myIpv4?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myIpv6?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myUuid?: string; - /** - * - * @type {string} - * @memberof DataTypes200Response - */ - myByte?: string; - /** - * - * @type {Date} - * @memberof DataTypes200Response - */ - myDateTime?: Date; +export interface DataTypes200ResponseMyObjectOneTwo { /** * * @type {string} - * @memberof DataTypes200Response - */ - myRegexPattern?: string; - /** - * - * @type {any} - * @memberof DataTypes200Response - */ - myOneOf?: any | null; - /** - * - * @type {any} - * @memberof DataTypes200Response + * @memberof DataTypes200ResponseMyObjectOneTwo */ - myAnyOf?: any | null; - /** - * - * @type {any} - * @memberof DataTypes200Response - */ - myAllOf?: any | null; - /** - * - * @type {any} - * @memberof DataTypes200Response - */ - myNot?: any | null; - /** - * - * @type {any} - * @memberof DataTypes200Response - */ - myNotString?: any | null; - /** - * - * @type {{ [key: string]: Array; }} - * @memberof DataTypes200Response - */ - myAdditionalProperties?: { [key: string]: Array; }; + threeString?: string; } /** - * Check if a given object implements the DataTypes200Response interface. + * Check if a given object implements the DataTypes200ResponseMyObjectOneTwo interface. */ -export function instanceOfDataTypes200Response(value: object): boolean { +export function instanceOfDataTypes200ResponseMyObjectOneTwo(value: object): boolean { let isInstance = true; - return isInstance; } -export function DataTypes200ResponseFromJSON(json: any): DataTypes200Response { - return DataTypes200ResponseFromJSONTyped(json, false); +export function DataTypes200ResponseMyObjectOneTwoFromJSON(json: any): DataTypes200ResponseMyObjectOneTwo { + return DataTypes200ResponseMyObjectOneTwoFromJSONTyped(json, false); } -export function DataTypes200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200Response { +export function DataTypes200ResponseMyObjectOneTwoFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyObjectOneTwo { if ((json === undefined) || (json === null)) { return json; } return { - 'myInt': !exists(json, 'myInt') ? undefined : json['myInt'], - 'myString': !exists(json, 'myString') ? undefined : json['myString'], - 'myStringLength': !exists(json, 'myStringLength') ? undefined : json['myStringLength'], - 'myLongMinStringLength': !exists(json, 'myLongMinStringLength') ? undefined : json['myLongMinStringLength'], - 'myBool': !exists(json, 'myBool') ? undefined : json['myBool'], - 'myNumber': !exists(json, 'myNumber') ? undefined : json['myNumber'], - 'myDateArray': !exists(json, 'myDateArray') ? undefined : json['myDateArray'], - 'myEmail': !exists(json, 'myEmail') ? undefined : json['myEmail'], - 'myUrl': !exists(json, 'myUrl') ? undefined : json['myUrl'], - 'myHostname': !exists(json, 'myHostname') ? undefined : json['myHostname'], - 'myIpv4': !exists(json, 'myIpv4') ? undefined : json['myIpv4'], - 'myIpv6': !exists(json, 'myIpv6') ? undefined : json['myIpv6'], - 'myUuid': !exists(json, 'myUuid') ? undefined : json['myUuid'], - 'myByte': !exists(json, 'myByte') ? undefined : json['myByte'], - 'myDateTime': !exists(json, 'myDateTime') ? undefined : (new Date(json['myDateTime'])), - 'myRegexPattern': !exists(json, 'myRegexPattern') ? undefined : json['myRegexPattern'], - 'myOneOf': !exists(json, 'myOneOf') ? undefined : json['myOneOf'], - 'myAnyOf': !exists(json, 'myAnyOf') ? undefined : json['myAnyOf'], - 'myAllOf': !exists(json, 'myAllOf') ? undefined : json['myAllOf'], - 'myNot': !exists(json, 'myNot') ? undefined : json['myNot'], - 'myNotString': !exists(json, 'myNotString') ? undefined : json['myNotString'], - 'myAdditionalProperties': !exists(json, 'myAdditionalProperties') ? undefined : json['myAdditionalProperties'], + 'threeString': !exists(json, 'threeString') ? undefined : json['threeString'], }; } -export function DataTypes200ResponseToJSON(value?: DataTypes200Response | null): any { +export function DataTypes200ResponseMyObjectOneTwoToJSON(value?: DataTypes200ResponseMyObjectOneTwo | null): any { if (value === undefined) { return undefined; } @@ -2502,35 +6293,86 @@ export function DataTypes200ResponseToJSON(value?: DataTypes200Response | null): } return { - 'myInt': value.myInt, - 'myString': value.myString, - 'myStringLength': value.myStringLength, - 'myLongMinStringLength': value.myLongMinStringLength, - 'myBool': value.myBool, - 'myNumber': value.myNumber, - 'myDateArray': value.myDateArray, - 'myEmail': value.myEmail, - 'myUrl': value.myUrl, - 'myHostname': value.myHostname, - 'myIpv4': value.myIpv4, - 'myIpv6': value.myIpv6, - 'myUuid': value.myUuid, - 'myByte': value.myByte, - 'myDateTime': value.myDateTime === undefined ? undefined : (value.myDateTime.toISOString()), - 'myRegexPattern': value.myRegexPattern, - 'myOneOf': value.myOneOf, - 'myAnyOf': value.myAnyOf, - 'myAllOf': value.myAllOf, - 'myNot': value.myNot, - 'myNotString': value.myNotString, - 'myAdditionalProperties': value.myAdditionalProperties, + 'threeString': value.threeString, }; } +", + "src/models/DataTypes200ResponseMyOneOf.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Data Types + * + * + * 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'; + +/** + * @type DataTypes200ResponseMyOneOf + * + * @export + */ +export type DataTypes200ResponseMyOneOf = string | number; + + +/** + * Check if a given object implements the DataTypes200ResponseMyOneOf interface. + */ +export function instanceOfDataTypes200ResponseMyOneOf(value: object): boolean { + return typeof value === "string" || typeof value === "number" +} + +export function DataTypes200ResponseMyOneOfFromJSON(json: any): DataTypes200ResponseMyOneOf { + return DataTypes200ResponseMyOneOfFromJSONTyped(json, false); +} + +export function DataTypes200ResponseMyOneOfFromJSONTyped(json: any, ignoreDiscriminator: boolean): DataTypes200ResponseMyOneOf { + if ((json === undefined) || (json === null)) { + return json; + } + if (typeof json === "string") { + return json; + } + if (typeof json === "number") { + return json; + } + return json; +} + +export function DataTypes200ResponseMyOneOfToJSON(value?: DataTypes200ResponseMyOneOf | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + if (typeof value === "string") { + return value; + } + if (typeof value === "number") { + return value; + } + return value; +} + ", "src/models/index.ts": "/* tslint:disable */ /* eslint-disable */ export * from './DataTypes200Response'; +export * from './DataTypes200ResponseMyAllOf'; +export * from './DataTypes200ResponseMyAllOfAllOf'; +export * from './DataTypes200ResponseMyAllOfAllOf1'; +export * from './DataTypes200ResponseMyAnyOf'; +export * from './DataTypes200ResponseMyNotNot'; +export * from './DataTypes200ResponseMyObject'; +export * from './DataTypes200ResponseMyObjectOne'; +export * from './DataTypes200ResponseMyObjectOneTwo'; +export * from './DataTypes200ResponseMyOneOf'; ", "src/models/model-utils.ts": "/* tslint:disable */ /* eslint-disable */ @@ -3831,7 +7673,6 @@ export interface HelloId { */ export function instanceOfHelloId(value: object): boolean { let isInstance = true; - return isInstance; } @@ -3866,6 +7707,7 @@ import { HelloIdFromJSON, HelloIdFromJSONTyped, HelloIdToJSON, + instanceOfHelloId, } from './HelloId'; /** @@ -3895,7 +7737,6 @@ export interface SayHelloResponseContent { export function instanceOfSayHelloResponseContent(value: object): boolean { let isInstance = true; isInstance = isInstance && "message" in value; - return isInstance; } @@ -3964,7 +7805,6 @@ export interface ServiceUnavailableErrorResponseContent { export function instanceOfServiceUnavailableErrorResponseContent(value: object): boolean { let isInstance = true; isInstance = isInstance && "message" in value; - return isInstance; } @@ -5488,6 +9328,8 @@ export type MyEnum = 'three' + + export function MyEnumFromJSON(json: any): MyEnum { return MyEnumFromJSONTyped(json, false); } @@ -8488,7 +12330,6 @@ export interface HelloId { */ export function instanceOfHelloId(value: object): boolean { let isInstance = true; - return isInstance; } @@ -8523,12 +12364,14 @@ import { HelloIdFromJSON, HelloIdFromJSONTyped, HelloIdToJSON, + instanceOfHelloId, } from './HelloId'; import type { HelloResponse } from './HelloResponse'; import { HelloResponseFromJSON, HelloResponseFromJSONTyped, HelloResponseToJSON, + instanceOfHelloResponse, } from './HelloResponse'; /** @@ -8558,7 +12401,6 @@ export interface HelloResponse { export function instanceOfHelloResponse(value: object): boolean { let isInstance = true; isInstance = isInstance && "id" in value; - return isInstance; } @@ -10877,7 +14719,6 @@ export interface ApiError { export function instanceOfApiError(value: object): boolean { let isInstance = true; isInstance = isInstance && "errorMessage" in value; - return isInstance; } @@ -10927,6 +14768,7 @@ import { MapResponseMapPropertyValueFromJSON, MapResponseMapPropertyValueFromJSONTyped, MapResponseMapPropertyValueToJSON, + instanceOfMapResponseMapPropertyValue, } from './MapResponseMapPropertyValue'; /** @@ -10950,7 +14792,6 @@ export interface MapResponse { export function instanceOfMapResponse(value: object): boolean { let isInstance = true; isInstance = isInstance && "mapProperty" in value; - return isInstance; } @@ -11023,7 +14864,6 @@ export interface MapResponseMapPropertyValue { export function instanceOfMapResponseMapPropertyValue(value: object): boolean { let isInstance = true; isInstance = isInstance && "a" in value; - return isInstance; } @@ -11091,7 +14931,6 @@ export interface TestRequest { */ export function instanceOfTestRequest(value: object): boolean { let isInstance = true; - return isInstance; } @@ -11141,6 +14980,7 @@ import { TestResponseMessagesInnerFromJSON, TestResponseMessagesInnerFromJSONTyped, TestResponseMessagesInnerToJSON, + instanceOfTestResponseMessagesInner, } from './TestResponseMessagesInner'; /** @@ -11164,7 +15004,6 @@ export interface TestResponse { export function instanceOfTestResponse(value: object): boolean { let isInstance = true; isInstance = isInstance && "messages" in value; - return isInstance; } @@ -11237,7 +15076,6 @@ export interface TestResponseMessagesInner { export function instanceOfTestResponseMessagesInner(value: object): boolean { let isInstance = true; isInstance = isInstance && "id" in value; - return isInstance; } diff --git a/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript-websocket-client.test.ts.snap b/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript-websocket-client.test.ts.snap index d54a4d3c7..44fd2eaa1 100644 --- a/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript-websocket-client.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript-websocket-client.test.ts.snap @@ -563,7 +563,6 @@ export interface ApiError { export function instanceOfApiError(value: object): boolean { let isInstance = true; isInstance = isInstance && "errorMessage" in value; - return isInstance; } @@ -613,6 +612,7 @@ import { MapRequestMapPropertyValueFromJSON, MapRequestMapPropertyValueFromJSONTyped, MapRequestMapPropertyValueToJSON, + instanceOfMapRequestMapPropertyValue, } from './MapRequestMapPropertyValue'; /** @@ -636,7 +636,6 @@ export interface MapRequest { export function instanceOfMapRequest(value: object): boolean { let isInstance = true; isInstance = isInstance && "mapProperty" in value; - return isInstance; } @@ -709,7 +708,6 @@ export interface MapRequestMapPropertyValue { export function instanceOfMapRequestMapPropertyValue(value: object): boolean { let isInstance = true; isInstance = isInstance && "a" in value; - return isInstance; } @@ -777,7 +775,6 @@ export interface TestRequest { */ export function instanceOfTestRequest(value: object): boolean { let isInstance = true; - return isInstance; } @@ -827,6 +824,7 @@ import { TestResponseMessagesInnerFromJSON, TestResponseMessagesInnerFromJSONTyped, TestResponseMessagesInnerToJSON, + instanceOfTestResponseMessagesInner, } from './TestResponseMessagesInner'; /** @@ -850,7 +848,6 @@ export interface TestResponse { export function instanceOfTestResponse(value: object): boolean { let isInstance = true; isInstance = isInstance && "messages" in value; - return isInstance; } @@ -923,7 +920,6 @@ export interface TestResponseMessagesInner { export function instanceOfTestResponseMessagesInner(value: object): boolean { let isInstance = true; isInstance = isInstance && "id" in value; - return isInstance; } diff --git a/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript.test.ts.snap b/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript.test.ts.snap index 3d702277c..fb08aed05 100644 --- a/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/async/__snapshots__/typescript.test.ts.snap @@ -240,7 +240,6 @@ export interface ApiError { export function instanceOfApiError(value: object): boolean { let isInstance = true; isInstance = isInstance && "errorMessage" in value; - return isInstance; } @@ -290,6 +289,7 @@ import { MapRequestMapPropertyValueFromJSON, MapRequestMapPropertyValueFromJSONTyped, MapRequestMapPropertyValueToJSON, + instanceOfMapRequestMapPropertyValue, } from './MapRequestMapPropertyValue'; /** @@ -313,7 +313,6 @@ export interface MapRequest { export function instanceOfMapRequest(value: object): boolean { let isInstance = true; isInstance = isInstance && "mapProperty" in value; - return isInstance; } @@ -386,7 +385,6 @@ export interface MapRequestMapPropertyValue { export function instanceOfMapRequestMapPropertyValue(value: object): boolean { let isInstance = true; isInstance = isInstance && "a" in value; - return isInstance; } @@ -454,7 +452,6 @@ export interface TestRequest { */ export function instanceOfTestRequest(value: object): boolean { let isInstance = true; - return isInstance; } @@ -504,6 +501,7 @@ import { TestResponseMessagesInnerFromJSON, TestResponseMessagesInnerFromJSONTyped, TestResponseMessagesInnerToJSON, + instanceOfTestResponseMessagesInner, } from './TestResponseMessagesInner'; /** @@ -527,7 +525,6 @@ export interface TestResponse { export function instanceOfTestResponse(value: object): boolean { let isInstance = true; isInstance = isInstance && "messages" in value; - return isInstance; } @@ -600,7 +597,6 @@ export interface TestResponseMessagesInner { export function instanceOfTestResponseMessagesInner(value: object): boolean { let isInstance = true; isInstance = isInstance && "id" in value; - return isInstance; } diff --git a/packages/type-safe-api/test/scripts/generators/java.test.ts b/packages/type-safe-api/test/scripts/generators/java.test.ts index b43cb3986..dda868d8c 100644 --- a/packages/type-safe-api/test/scripts/generators/java.test.ts +++ b/packages/type-safe-api/test/scripts/generators/java.test.ts @@ -16,6 +16,7 @@ describe("Java Client Code Generation Script Unit Tests", () => { "parameter-refs.yaml", "default-response.yaml", "allof-model.yaml", + "composite-models.yaml", ])("Generates With %s", (spec) => { const specPath = path.resolve(__dirname, `../../resources/specs/${spec}`); diff --git a/packages/type-safe-api/test/scripts/generators/python.test.ts b/packages/type-safe-api/test/scripts/generators/python.test.ts index 55c464206..5dba272b4 100644 --- a/packages/type-safe-api/test/scripts/generators/python.test.ts +++ b/packages/type-safe-api/test/scripts/generators/python.test.ts @@ -15,6 +15,7 @@ describe("Python Client Code Generation Script Unit Tests", () => { "parameter-refs.yaml", "default-response.yaml", "allof-model.yaml", + "composite-models.yaml", ])("Generates With %s", (spec) => { const specPath = path.resolve(__dirname, `../../resources/specs/${spec}`); diff --git a/packages/type-safe-api/test/scripts/generators/typescript.test.ts b/packages/type-safe-api/test/scripts/generators/typescript.test.ts index 20c6b3516..f7d163290 100644 --- a/packages/type-safe-api/test/scripts/generators/typescript.test.ts +++ b/packages/type-safe-api/test/scripts/generators/typescript.test.ts @@ -15,6 +15,7 @@ describe("Typescript Client Code Generation Script Unit Tests", () => { "parameter-refs.yaml", "default-response.yaml", "allof-model.yaml", + "composite-models.yaml", ])("Generates With %s", (spec) => { const specPath = path.resolve(__dirname, `../../resources/specs/${spec}`);