Compare commits

...

19 Commits

Author SHA1 Message Date
William Cheng
8ecf9e352d fix additional properties any type 2023-07-30 16:25:18 +08:00
William Cheng
07d4f7d534 update template and samples 2023-07-30 16:20:45 +08:00
William Cheng
659885f509 better additional properties support 2023-07-30 16:15:07 +08:00
William Cheng
526ca78e79 add tests for #16199 (python client) (#16220) 2023-07-30 01:19:11 +08:00
ふぁ
48ff57b4f6 [python-nextgen] fix #16010 circular refs lead to no imports (#16199)
* [python-nextgen] fix #16010 circular refs lead to no imports

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] remove unnecessary Postponed annotations

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] remove unnecessary Postponed annotations

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

---------

Signed-off-by: ふぁ <yuki@yuki0311.com>
2023-07-30 00:42:46 +08:00
William Cheng
d41fe12c1f [python] Add tests for simple object with additional properties (#16218)
* add tests for simple object without additional properties

* update logic
2023-07-29 11:43:37 +08:00
ふぁ
d9fc039dcf [python-nextgen] fix #16151 Disallow additional properties if not present - missing Any and Dict import (#16208)
* [python-nextgen] fix #16151 Disallow additional properties if not present - missing Any and Dict import

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] remove unwanted imports

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] remove unwanted imports

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

---------

Signed-off-by: ふぁ <yuki@yuki0311.com>
2023-07-29 10:51:28 +08:00
ふぁ
e411b2ac0a [python-nextgen] Add type to actual instance (#16204)
* [python-nextgen] add type to actual_instance

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] fixed unnecessary type conversions

Signed-off-by: ふぁ <yuki@yuki0311.com>

* [python-nextgen] update samples

Signed-off-by: ふぁ <yuki@yuki0311.com>

---------

Signed-off-by: ふぁ <yuki@yuki0311.com>
2023-07-29 10:08:06 +08:00
Marc Miltenberger
adac3b127f Support for multipart/form-data; charset="utf-8" in Java GSON Generator (#16211)
* Support for multipart/form-data; charset="utf-8"

Previously, it was only checked for an exact equal string, which failed when there were additional options such as charset.

* Update samples
2023-07-29 00:22:19 +08:00
William Cheng
7ca84e5c88 Add name, parameter name mapping to abstract go codegen (#16171)
* add name, parameter name mapping to abstract go codegen

* better code format
2023-07-28 09:57:23 +08:00
William Cheng
5d2e80977b add name, parameter mapping to scala generators (#16194) 2023-07-28 09:51:50 +08:00
William Cheng
954d41b9aa [C#] Add property, parameter naming support (#16196)
* add property, parameter naming support to c# generators

* update

* fix workflow

* update test

* update
2023-07-28 09:51:33 +08:00
William Cheng
184dfd2edd [Kotlin] Add name, parameter mapping support (#16193)
* add name, parameter mapping support to abstract kotlin

* remove files
2023-07-28 09:42:08 +08:00
William Cheng
86cf4f1eb1 add mapping option to ada codegen (#16190) 2023-07-28 09:41:43 +08:00
Masahiro Sakai
f6a819686d [haskell][haskell-yesod] Fix special char replacements (#16197)
* [haskell][haskell-yesod] remove fixOperatorChars()

fixOperatorChars() does not change input strings since special
characters have already been replaced in DefaultCodegen.fromModel().

* [haskell][haskell-yesod] do not prefix with quote ("'") when generating removeFieldLabelPrefix table

We switched from the conversion done by fixOperatorChars() to the
conversion done by DefaultCodegen.fromModel() and the latter does not
insert quote characters. So We modify the removeFieldLabelPrefix table
to conform the new mapping.

* [haskell][haskell-yesod] remove forParsing parameter from removeFieldLabelPrefix function

Aeson's fieldLabelModifier always convert Haskell field names to JSON
field names, whether at parse time or not. (Note that stripPrefix and
uncapitalize do not take such parameter)

* [haskell][haskell-yesod] perform replaceSpecialChars after stripping prefix

Because replaceSpecialChars can corrupt prefix if the prefix contains
a replacement string of a specfial character as a substring.

* [haskell][haskell-yesod] regenerate samples
2023-07-28 09:35:46 +08:00
William Cheng
d7311cd5cd [Ruby] add property, parameter name mapping (#16191)
* add property, parameter name mapping support to ruby generators

* update samples
2023-07-27 09:48:53 +08:00
Adam Shannon
90eacb685c fix(golang): make sure xml.Encoder is closed (#16141) 2023-07-26 15:48:46 +08:00
William Cheng
30c38ed7ad fix potential npe in ada codegen (#16188) 2023-07-26 14:12:45 +08:00
William Cheng
596487aa6c update doc, customization.md (#16189) 2023-07-26 14:11:36 +08:00
362 changed files with 11985 additions and 555 deletions

View File

@@ -20,6 +20,8 @@ on:
- samples/client/petstore/csharp/OpenAPIClient-net5.0/**
# build C# API client (.net 5.0 with ConditionalSerialization)
- samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/**
# build C# API client (property, parameter name mappings)
- samples/client/petstore/csharp-restsharp-name-parameter-mappings/**
pull_request:
paths:
# build C# API client (multiple frameworks)
@@ -39,6 +41,8 @@ on:
- samples/client/petstore/csharp/OpenAPIClient-net5.0/**
# build C# API client (.net 5.0 with ConditionalSerialization)
- samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/**
# build C# API client (property, parameter name mappings)
- samples/client/petstore/csharp-restsharp-name-parameter-mappings/**
jobs:
build:
name: Build .Net clients
@@ -65,6 +69,8 @@ jobs:
- samples/client/petstore/csharp/OpenAPIClient-net5.0/
# build C# API client (.net 5.0 with ConditionalSerialization)
- samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/
# build C# API client (property, parameter name mappings)
- samples/client/petstore/csharp-restsharp-name-parameter-mappings
steps:
- uses: actions/checkout@v3
- uses: actions/setup-dotnet@v3.2.0

View File

@@ -59,6 +59,7 @@ jobs:
- samples/client/petstore/kotlin-jvm-spring-2-webclient
- samples/client/petstore/kotlin-jvm-spring-3-webclient
- samples/client/petstore/kotlin-spring-cloud
- samples/client/petstore/kotlin-name-parameter-mappings
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3

View File

@@ -115,13 +115,15 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
| OpenAPI Generator Version | Release Date | Notes |
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- |
| 7.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.0.0-SNAPSHOT/) | May/Jun 2023 | Major release with breaking changes (no fallback) |
| 7.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.0.0-SNAPSHOT/) | Jul/Aug 2023 | Major release with breaking changes (no fallback) |
| [6.6.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v6.6.0) (latest stable release) | 11.05.2023 | Minor release with breaking changes (with fallback) |
| [5.4.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.4.0) | 31.01.2022 | Minor release with breaking changes (with fallback) |
| [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) |
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
(We do not publish daily/nightly build. Please use SNAPSHOT instead)
For old releases, please refer to the [**Release**](https://github.com/OpenAPITools/openapi-generator/releases) page.
For decomissioned generators/libraries/frameworks, please refer to [the "Decommission" label](https://github.com/OpenAPITools/openapi-generator/issues?q=label%3ADecommission+is%3Amerged+) in the pull request page.
@@ -906,6 +908,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2023-04-27 - [Create an Angular Client using OpenAPI Specifications](Create an Angular Client using OpenAPI Specifications) by [Patric](https://pguso.medium.com/)
- 2023-05-16 - [Adyen for Java developers](https://www.adyen.com/blog/adyen-java-library) by [Beppe Catanese, Developer Advocate, Adyen](https://github.com/gcatanese)
- 2023-05-18 - [如何基于 Swagger 使用 OpenAPI Generator 生成 JMeter 脚本?](https://blog.51cto.com/u_15181572/6294974) by [高楼Zee)](https://blog.51cto.com/u_15181572)
- 2023-06-28 - [Generate API contract using OpenAPI Generator Maven plugin](https://huongdanjava.com/generate-api-contract-using-openapi-generator-maven-plugin.html) by [Khanh Nguyen](https://huongdanjava.com/)
- 2023-06-30 - [Generate Client SDKs with OpenApi Generator in Springboot](https://medium.com/@ramavathvinayak/generate-client-sdks-with-openapi-generator-in-springboot-f9f012e73c0b) by [Vinayak Ramavath](https://medium.com/@ramavathvinayak)
## [6 - About Us](#table-of-contents)

15
bin/configs/ada.yaml Normal file
View File

@@ -0,0 +1,15 @@
generatorName: ada
outputDir: samples/client/petstore/ada
inputSpec: modules/openapi-generator/src/test/resources/3_0/ada/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/Ada
nameMappings:
_type: P_UnderscoreType
type_: P_TypeWithUnderscore
http_debug_operation: P_HTTPDebugOperation
parameterNameMappings:
_type: UnderscoreType
type_: TypeWithUnderscore
http_debug_operation: HttpDebugOperation
additionalProperties:
modelPackage: Samples.Petstore
projectName: Petstore

View File

@@ -0,0 +1,15 @@
generatorName: csharp
outputDir: samples/client/petstore/csharp-restsharp-name-parameter-mappings
inputSpec: modules/openapi-generator/src/test/resources/3_0/name-parameter-mappings.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp
nameMappings:
_type: UnderscoreType
type_: TypeWithUnderscore
http_debug_operation: HttpDebugOperation
parameterNameMappings:
_type: UnderscoreType
type_: TypeWithUnderscore
http_debug_operation: HttpDebugOperation
additionalProperties:
packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'
hideGenerationTimestamp: "true"

View File

@@ -2,8 +2,17 @@ generatorName: go
outputDir: samples/openapi3/client/petstore/go/go-petstore
inputSpec: modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/go
nameMappings:
_type: UnderscoreType
type_: TypeWithUnderscore
http_debug_operation: HTTPDebugOperation
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
http_debug_operation: httpDebugOperation
additionalProperties:
enumClassPrefix: "true"
packageName: petstore
disallowAdditionalPropertiesIfNotPresent: false
generateInterfaces: true

View File

@@ -0,0 +1,14 @@
generatorName: kotlin
outputDir: samples/client/petstore/kotlin-name-parameter-mappings
inputSpec: modules/openapi-generator/src/test/resources/3_0/name-parameter-mappings.yaml
templateDir: modules/openapi-generator/src/main/resources/kotlin-client
nameMappings:
_type: underscoreType
type_: typeWithUnderscore
http_debug_operation: httpDebugOperation
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
http_debug_operation: httpDebugOperation
additionalProperties:
artifactId: kotlin-petstore-client

View File

@@ -9,3 +9,9 @@ additionalProperties:
gemName: petstore
skipFormModel: "true"
strictSpecBehavior: false
nameMappings:
_type: underscore_type
type_: type_with_underscore
parameterNameMappings:
_type: underscore_type
type_: type_with_underscore

View File

@@ -2,5 +2,13 @@ generatorName: scala-sttp
outputDir: samples/client/petstore/scala-sttp
inputSpec: modules/openapi-generator/src/test/resources/3_0/scala/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/scala-sttp
nameMappings:
_type: "`underscoreType`"
type_: "`typeWithUnderscore`"
http_debug_operation: "`httpDebugOperation`"
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
http_debug_operation: httpDebugOperation
additionalProperties:
artifactId: scala-sttp-petstore

View File

@@ -1,7 +0,0 @@
generatorName: ada
outputDir: samples/client/petstore/ada
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/Ada
additionalProperties:
modelPackage: Samples.Petstore
projectName: Petstore

View File

@@ -536,7 +536,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer SET_TAGS_FOR_ALL_OPERATIONS=true
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer SET_TAGS_FOR_ALL_OPERATIONS=another_tag_name
```
- `ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE`: when set to true, auto fix integer with maximum value 4294967295 (2^32-1) or long with 18446744073709551615 (2^64-1) by adding x-unsigned to the schema

View File

@@ -153,6 +153,23 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
*/
public boolean isAdditionalPropertiesTrue;
/**
* True if additional properties is set to any type
*/
public boolean isAdditionalPropertiesAnyType;
/**
* True if additional properties is set to free form object
*/
public boolean isAdditionalPropertiesFreeFormObject;
/**
* True if additional properties is enabled (boolean or any type)
*/
public boolean isAdditionalPropertiesEnabled() {
return isAdditionalPropertiesTrue || isAdditionalPropertiesAnyType || isAdditionalPropertiesFreeFormObject;
}
private Integer maxProperties;
private Integer minProperties;
private boolean uniqueItems;
@@ -1088,6 +1105,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
Objects.equals(externalDocumentation, that.externalDocumentation) &&
Objects.equals(vendorExtensions, that.vendorExtensions) &&
Objects.equals(additionalPropertiesType, that.additionalPropertiesType) &&
Objects.equals(isAdditionalPropertiesAnyType, that.isAdditionalPropertiesAnyType) &&
Objects.equals(isAdditionalPropertiesFreeFormObject, that.isAdditionalPropertiesFreeFormObject) &&
Objects.equals(isAdditionalPropertiesTrue, that.isAdditionalPropertiesTrue) &&
Objects.equals(getMaxProperties(), that.getMaxProperties()) &&
Objects.equals(getMinProperties(), that.getMinProperties()) &&
Objects.equals(getMaxItems(), that.getMaxItems()) &&
@@ -1121,7 +1141,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
getAdditionalPropertiesIsAnyType(), hasDiscriminatorWithNonEmptyMapping,
isAnyType, getComposedSchemas(), hasMultipleTypes, isDecimal, isUuid, requiredVarsMap, ref,
uniqueItemsBoolean, schemaIsFromAdditionalProperties, isBooleanSchemaTrue, isBooleanSchemaFalse,
format, dependentRequired, contains);
format, dependentRequired, contains, isAdditionalPropertiesTrue, isAdditionalPropertiesFreeFormObject,
isAdditionalPropertiesFreeFormObject);
}
@Override
@@ -1227,6 +1248,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
sb.append(", format=").append(format);
sb.append(", dependentRequired=").append(dependentRequired);
sb.append(", contains=").append(contains);
sb.append(", isAdditionalPropertiesAnyType=").append(isAdditionalPropertiesAnyType);
sb.append(", isAdditionalPropertiesFreeFormObject=").append(isAdditionalPropertiesFreeFormObject);
sb.append(", isAdditionalPropertiesTrue=").append(isAdditionalPropertiesTrue);
sb.append('}');
return sb.toString();
}

View File

@@ -1617,6 +1617,11 @@ public class DefaultCodegen implements CodegenConfig {
* @return the sanitized variable name
*/
public String toVarName(final String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
} else if (name.chars().anyMatch(character -> specialCharReplacements.containsKey(String.valueOf((char) character)))) {
@@ -1634,6 +1639,11 @@ public class DefaultCodegen implements CodegenConfig {
*/
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
name = removeNonNameElementToCamelCase(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
@@ -3157,13 +3167,16 @@ public class DefaultCodegen implements CodegenConfig {
// if we are trying to set additionalProperties on an empty schema stop recursing
return;
}
boolean additionalPropertiesIsAnyType = false;
boolean isAdditionalPropertiesTrue = false;
boolean isAdditionalPropertiesFreeFormObject = false;
CodegenModel m = null;
if (property instanceof CodegenModel) {
m = (CodegenModel) property;
}
CodegenProperty addPropProp = null;
boolean isAdditionalPropertiesTrue = false;
if (schema.getAdditionalProperties() == null) {
if (!disallowAdditionalPropertiesIfNotPresent) {
isAdditionalPropertiesTrue = true;
@@ -3173,20 +3186,25 @@ public class DefaultCodegen implements CodegenConfig {
} else if (schema.getAdditionalProperties() instanceof Boolean) {
if (Boolean.TRUE.equals(schema.getAdditionalProperties())) {
isAdditionalPropertiesTrue = true;
addPropProp = fromProperty(getAdditionalPropertiesName(), new Schema(), false);
additionalPropertiesIsAnyType = true;
}
} else {
addPropProp = fromProperty(getAdditionalPropertiesName(), (Schema) schema.getAdditionalProperties(), false);
if (ModelUtils.isAnyType((Schema) schema.getAdditionalProperties())) {
isAdditionalPropertiesTrue = true;
additionalPropertiesIsAnyType = true;
}
if (ModelUtils.isFreeFormObject((Schema) schema.getAdditionalProperties())) {
isAdditionalPropertiesFreeFormObject = true;
}
}
if (additionalPropertiesIsAnyType) {
property.setAdditionalPropertiesIsAnyType(true);
}
if (m != null && isAdditionalPropertiesTrue) {
m.isAdditionalPropertiesTrue = true;
if (m != null) {
m.isAdditionalPropertiesTrue = isAdditionalPropertiesTrue;
m.isAdditionalPropertiesAnyType = additionalPropertiesIsAnyType;
m.isAdditionalPropertiesFreeFormObject = isAdditionalPropertiesFreeFormObject;
}
if (ModelUtils.isComposedSchema(schema) && !supportsAdditionalPropertiesWithComposedSchema) {
return;

View File

@@ -364,11 +364,21 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
return toAdaIdentifier(sanitizeName(name), "P_");
}
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
return toAdaIdentifier(super.toParamName(name), "P_");
}
@@ -821,7 +831,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
//LOGGER.debug("Compare " + name + " with " + second.name + "=-1");
return -1;
}
if ((depend == null ? 0 : depend.size()) != (second.depend == null ? 0 : second.depend.size())) {
if (depend != null && (depend == null ? 0 : depend.size()) != (second.depend == null ? 0 : second.depend.size())) {
//LOGGER.debug("Compare " + name + " with " + second.name + "=D"
// + (depend.size() - second.depend.size()));
return depend.size() - second.depend.size();
@@ -833,7 +843,6 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
@Override
public ModelsMap postProcessModels(ModelsMap objs) {
// This is run first, before the operations.
// remove model imports to avoid error
List<Map<String, String>> imports = objs.getImports();

View File

@@ -963,6 +963,11 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
// sanitize name
name = sanitizeName(name);
@@ -989,6 +994,11 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
// sanitize name
name = sanitizeName(name);

View File

@@ -191,6 +191,10 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
// replace - with _ e.g. created-at => created_at
name = sanitizeName(name);
@@ -228,6 +232,11 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
// params should be lowerCamelCase. E.g. "person Person", instead of
// "Person Person".
//
@@ -364,7 +373,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
return "[]" + typDecl;
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return getSchemaType(p) + "[string]" + getTypeDeclaration(unaliasSchema(inner));
return getSchemaType(p) + "[string]" + getTypeDeclaration(unaliasSchema(inner));
}
//return super.getTypeDeclaration(p);
@@ -621,7 +630,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
}
List<CodegenProperty> codegenProperties = new ArrayList<>();
if(model.getComposedSchemas() == null || (model.getComposedSchemas() != null && model.getComposedSchemas().getAllOf() != null)) {
if (model.getComposedSchemas() == null || (model.getComposedSchemas() != null && model.getComposedSchemas().getAllOf() != null)) {
// If the model is an allOf or does not have any composed schemas, then we can use the model's properties.
codegenProperties.addAll(model.vars);
} else {

View File

@@ -937,6 +937,11 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
// to avoid conflicts with 'callback' parameter for async call
if ("callback".equals(name)) {
return "paramCallback";
@@ -948,6 +953,11 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
name = toVariableName(name);
if (propertyAdditionalKeywords.contains(name)) {
return camelize("property_" + name, LOWERCASE_FIRST_LETTER);

View File

@@ -176,6 +176,11 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override
public String toVarName(final String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
String varName = sanitizeName(name);
// if it's all upper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
@@ -201,6 +206,11 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
// should be the same as variable name
return toVarName(name);
}
@@ -265,5 +275,7 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
}
@Override
public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.RUBY; }
public GeneratorLanguage generatorLanguage() {
return GeneratorLanguage.RUBY;
}
}

View File

@@ -276,6 +276,11 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
String varName = sanitizeName(name);
if ("_".equals(varName)) {

View File

@@ -1259,6 +1259,11 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
// sanitize name
name = sanitizeName(name);

View File

@@ -928,6 +928,11 @@ public class CSharpReducedClientCodegen extends AbstractCSharpCodegen {
@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
// sanitize name
name = sanitizeName(name);

View File

@@ -326,7 +326,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
String c = (String) replacementChar;
Map<String, Object> o = new HashMap<>();
o.put("char", c);
o.put("replacement", "'" + specialCharReplacements.get(c));
o.put("replacement", specialCharReplacements.get(c));
replacements.add(o);
}
additionalProperties.put("specialCharReplacements", replacements);
@@ -636,29 +636,6 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
}
}
private String fixOperatorChars(String string) {
StringBuilder sb = new StringBuilder();
String name = string;
//Check if it is a reserved word, in which case the underscore is added when property name is generated.
if (string.startsWith("_")) {
if (reservedWords.contains(string.substring(1))) {
name = string.substring(1);
} else if (reservedWordsMappings.containsValue(string)) {
name = LEADING_UNDERSCORE.matcher(string).replaceFirst("");
}
}
for (char c : name.toCharArray()) {
String cString = String.valueOf(c);
if (specialCharReplacements.containsKey(cString)) {
sb.append("'");
sb.append(specialCharReplacements.get(cString));
} else {
sb.append(c);
}
}
return sb.toString();
}
// Remove characters from a string that do not belong in a model classname
private String fixModelChars(String string) {
return string.replace(".", "").replace("-", "");
@@ -680,7 +657,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// From the model name, compute the prefix for the fields.
String prefix = camelize(model.classname, LOWERCASE_FIRST_LETTER);
for (CodegenProperty prop : model.vars) {
prop.name = toVarName(prefix + camelize(fixOperatorChars(prop.name)));
prop.name = toVarName(prefix + camelize(prop.name));
}
// Create newtypes for things with non-object types

View File

@@ -286,7 +286,7 @@ public class HaskellYesodServerCodegen extends DefaultCodegen implements Codegen
String c = (String) replacementChar;
Map<String, Object> o = new HashMap<>();
o.put("char", c);
o.put("replacement", "'" + specialCharReplacements.get(c));
o.put("replacement", specialCharReplacements.get(c));
replacements.add(o);
}
additionalProperties.put("specialCharReplacements", replacements);
@@ -530,29 +530,6 @@ public class HaskellYesodServerCodegen extends DefaultCodegen implements Codegen
}
}
private String fixOperatorChars(String string) {
StringBuilder sb = new StringBuilder();
String name = string;
//Check if it is a reserved word, in which case the underscore is added when property name is generated.
if (string.startsWith("_")) {
if (reservedWords.contains(string.substring(1))) {
name = string.substring(1);
} else if (reservedWordsMappings.containsValue(string)) {
name = LEADING_UNDERSCORE.matcher(string).replaceFirst("");
}
}
for (char c : name.toCharArray()) {
String cString = String.valueOf(c);
if (specialCharReplacements.containsKey(cString)) {
sb.append("'");
sb.append(specialCharReplacements.get(cString));
} else {
sb.append(c);
}
}
return sb.toString();
}
// Remove characters from a string that do not belong in a model classname
private String fixModelChars(String string) {
return string.replace(".", "").replace("-", "");
@@ -574,7 +551,7 @@ public class HaskellYesodServerCodegen extends DefaultCodegen implements Codegen
// From the model name, compute the prefix for the fields.
String prefix = camelize(model.classname, LOWERCASE_FIRST_LETTER);
for (CodegenProperty prop : model.vars) {
prop.name = toVarName(prefix + camelize(fixOperatorChars(prop.name)));
prop.name = toVarName(prefix + camelize(prop.name));
}
// Create newtypes for things with non-object types

View File

@@ -413,6 +413,8 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
* @param datetimeImports datetime imports
* @param modelImports model imports
* @param exampleImports example imports
* @param postponedModelImports postponed model imports
* @param postponedExampleImports postponed example imports
* @param classname class name
* @return pydantic type
*
@@ -423,6 +425,8 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
Set<String> datetimeImports,
Set<String> modelImports,
Set<String> exampleImports,
Set<String> postponedModelImports,
Set<String> postponedExampleImports,
String classname) {
if (cp == null) {
// if codegen parameter (e.g. map/dict of undefined type) is null, default to string
@@ -444,12 +448,12 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
}
pydanticImports.add("conlist");
return String.format(Locale.ROOT, "conlist(%s%s)",
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, classname),
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, classname),
constraints);
} else if (cp.isMap) {
typingImports.add("Dict");
return String.format(Locale.ROOT, "Dict[str, %s]",
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, classname));
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, classname));
} else if (cp.isString) {
if (cp.hasValidation) {
List<String> fieldCustomization = new ArrayList<>();
@@ -658,7 +662,7 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
CodegenMediaType cmt = contents.get(key);
// TODO process the first one only at the moment
if (cmt != null)
return getPydanticType(cmt.getSchema(), typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, classname);
return getPydanticType(cmt.getSchema(), typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, classname);
}
throw new RuntimeException("Error! Failed to process getPydanticType when getting the content: " + cp);
} else {
@@ -675,6 +679,8 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
* @param datetimeImports datetime imports
* @param modelImports model imports
* @param exampleImports example imports
* @param postponedModelImports postponed model imports
* @param postponedExampleImports postponed example imports
* @param classname class name
* @return pydantic type
*
@@ -685,6 +691,8 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
Set<String> datetimeImports,
Set<String> modelImports,
Set<String> exampleImports,
Set<String> postponedModelImports,
Set<String> postponedExampleImports,
String classname) {
if (cp == null) {
// if codegen property (e.g. map/dict of undefined type) is null, default to string
@@ -725,11 +733,11 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
pydanticImports.add("conlist");
typingImports.add("List"); // for return type
return String.format(Locale.ROOT, "conlist(%s%s)",
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, classname),
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, classname),
constraints);
} else if (cp.isMap) {
typingImports.add("Dict");
return String.format(Locale.ROOT, "Dict[str, %s]", getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, classname));
return String.format(Locale.ROOT, "Dict[str, %s]", getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, classname));
} else if (cp.isString) {
if (cp.hasValidation) {
List<String> fieldCustomization = new ArrayList<>();
@@ -935,6 +943,9 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
} else {
if (circularImports.containsKey(cp.dataType)) {
if (circularImports.get(cp.dataType).contains(classname)) {
hasModelsToImport = true;
postponedModelImports.add(cp.dataType);
postponedExampleImports.add(cp.dataType);
// cp.dataType import map of set contains this model (classname), don't import
LOGGER.debug("Skipped importing {} in {} due to circular import.", cp.dataType, classname);
} else {
@@ -960,15 +971,17 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
TreeSet<String> pydanticImports = new TreeSet<>();
TreeSet<String> datetimeImports = new TreeSet<>();
TreeSet<String> modelImports = new TreeSet<>();
TreeSet<String> postponedModelImports = new TreeSet<>();
OperationMap objectMap = objs.getOperations();
List<CodegenOperation> operations = objectMap.getOperation();
for (CodegenOperation operation : operations) {
TreeSet<String> exampleImports = new TreeSet<>(); // import for each operation to be show in sample code
TreeSet<String> postponedExampleImports = new TreeSet<>(); // import for each operation to be show in sample code
List<CodegenParameter> params = operation.allParams;
for (CodegenParameter param : params) {
String typing = getPydanticType(param, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, null);
String typing = getPydanticType(param, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, null);
List<String> fields = new ArrayList<>();
String firstField = "";
@@ -1020,7 +1033,7 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
// update typing import for operation return type
if (!StringUtils.isEmpty(operation.returnType)) {
String typing = getPydanticType(operation.returnProperty, typingImports,
new TreeSet<>() /* skip pydantic import for return type */, datetimeImports, modelImports, exampleImports, null);
new TreeSet<>() /* skip pydantic import for return type */, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, null);
}
// add import for code samples
@@ -1032,6 +1045,15 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
}
operation.vendorExtensions.put("x-py-example-import", imports);
}
if (!postponedExampleImports.isEmpty()) {
List<String> imports = new ArrayList<>();
for (String exampleImport : postponedExampleImports) {
imports.add("from " + packageName + ".models." + underscore(exampleImport) + " import "
+ exampleImport);
}
operation.vendorExtensions.put("x-py-example-import", imports);
}
}
List<Map<String, String>> newImports = new ArrayList<>();
@@ -1066,6 +1088,14 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
}
}
if (!postponedModelImports.isEmpty()) {
for (String modelImport : postponedModelImports) {
Map<String, String> item = new HashMap<>();
item.put("import", "from " + packageName + ".models." + underscore(modelImport) + " import " + modelImport);
newImports.add(item);
}
}
// reset imports with newImports
objs.setImports(newImports);
return objs;
@@ -1194,9 +1224,11 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
TreeSet<String> pydanticImports = new TreeSet<>();
TreeSet<String> datetimeImports = new TreeSet<>();
TreeSet<String> modelImports = new TreeSet<>();
TreeSet<String> postponedModelImports = new TreeSet<>();
for (ModelMap m : objs.getModels()) {
TreeSet<String> exampleImports = new TreeSet<>();
TreeSet<String> postponedExampleImports = new TreeSet<>();
List<String> readOnlyFields = new ArrayList<>();
hasModelsToImport = false;
int property_count = 1;
@@ -1239,9 +1271,17 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
codegenProperties = model.vars;
}
// if model_generic.mustache is used and support additionalProperties
if (model.oneOf.isEmpty() && model.anyOf.isEmpty()
&& !model.isEnum
&& !this.disallowAdditionalPropertiesIfNotPresent) {
typingImports.add("Dict");
typingImports.add("Any");
}
//loop through properties/schemas to set up typing, pydantic
for (CodegenProperty cp : codegenProperties) {
String typing = getPydanticType(cp, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, model.classname);
String typing = getPydanticType(cp, typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, model.classname);
List<String> fields = new ArrayList<>();
String firstField = "";
@@ -1314,13 +1354,11 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
}
}
if (!model.isEnum) {
pydanticImports.add("BaseModel");
}
// add parent model to import
if (!StringUtils.isEmpty(model.parent)) {
modelImports.add(model.parent);
} else if (!model.isEnum) {
pydanticImports.add("BaseModel");
}
// set enum type in extensions and update `name` in enumVars
@@ -1356,6 +1394,20 @@ public class PythonClientCodegen extends AbstractPythonCodegen implements Codege
model.getVendorExtensions().putIfAbsent("x-py-model-imports", modelsToImport);
}
if (!postponedModelImports.isEmpty()) {
Set<String> modelsToImport = new TreeSet<>();
for (String modelImport : postponedModelImports) {
if (modelImport.equals(model.classname)) {
// skip self import
continue;
}
modelsToImport.add("from " + packageName + ".models." + underscore(modelImport) + " import " + modelImport);
}
model.getVendorExtensions().putIfAbsent("x-py-postponed-model-imports", modelsToImport);
}
}
return objs;

View File

@@ -159,15 +159,15 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code
if (additionalProperties.containsKey("mainPackage")) {
setMainPackage((String) additionalProperties.get("mainPackage"));
additionalProperties.replace("configKeyPath", this.configKeyPath);
if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)){
if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
apiPackage = mainPackage + ".api";
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
}
if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)){
if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
modelPackage = mainPackage + ".model";
additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
}
if (!additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)){
if (!additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
invokerPackage = mainPackage + ".core";
}
}
@@ -262,6 +262,11 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
return formatIdentifier(name, false);
}

View File

@@ -133,6 +133,11 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements Cod
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
// should be the same as variable name
return toVarName(name);
}

View File

@@ -380,6 +380,11 @@ public class ScalaSttp4ClientCodegen extends AbstractScalaCodegen implements Cod
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
return formatIdentifier(name, false);
}

View File

@@ -398,6 +398,11 @@ public class ScalaSttpClientCodegen extends AbstractScalaCodegen implements Code
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
return formatIdentifier(name, false);
}

View File

@@ -139,6 +139,11 @@ public class ScalazClientCodegen extends AbstractScalaCodegen implements Codegen
@Override
public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
// should be the same as variable name
return toVarName(name);
}

View File

@@ -1426,12 +1426,15 @@ public class ApiClient {
// prepare HTTP request body
RequestBody reqBody;
String contentType = headerParams.get("Content-Type");
String contentTypePure = contentType;
if (contentTypePure != null && contentTypePure.contains(";")) {
contentTypePure = contentType.substring(0, contentType.indexOf(";"));
}
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
} else if ("application/x-www-form-urlencoded".equals(contentTypePure)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentType)) {
} else if ("multipart/form-data".equals(contentTypePure)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {

View File

@@ -1,4 +1,4 @@
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
@@ -43,4 +43,4 @@
}
return this.additionalProperties.get(key);
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}

View File

@@ -314,8 +314,8 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} &&
{{/-last}}{{/vars}}{{#isAdditionalPropertiesTrue}}&&
Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/isAdditionalPropertiesTrue}}{{#parent}} &&
{{/-last}}{{/vars}}{{#isAdditionalPropertiesEnabled}}&&
Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/isAdditionalPropertiesEnabled}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}}
{{/useReflectionEqualsHashCode}}
@@ -331,7 +331,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
return HashCodeBuilder.reflectionHashCode(this);
{{/useReflectionEqualsHashCode}}
{{^useReflectionEqualsHashCode}}
return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#isAdditionalPropertiesTrue}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/isAdditionalPropertiesTrue}});
return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#isAdditionalPropertiesEnabled}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/isAdditionalPropertiesEnabled}});
{{/useReflectionEqualsHashCode}}
}{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
@@ -352,9 +352,9 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
{{#vars}}
sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n");
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
sb.append("}");
return sb.toString();
}
@@ -460,7 +460,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
}
}
{{^hasChildren}}
{{^isAdditionalPropertiesTrue}}
{{^isAdditionalPropertiesEnabled}}
Set<Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
@@ -469,7 +469,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `{{classname}}` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{#requiredVars}}
{{#-first}}
@@ -589,7 +589,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
@Override
public void write(JsonWriter out, {{classname}} value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
@@ -607,7 +607,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
}
}
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
elementAdapter.write(out, obj);
}
@@ -615,7 +615,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
public {{classname}} read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
{{classname}} instance = thisAdapter.fromJsonTree(jsonObj);
@@ -638,10 +638,10 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
}
}
return instance;
{{/isAdditionalPropertiesTrue}}
{{^isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{^isAdditionalPropertiesEnabled}}
return thisAdapter.fromJsonTree(jsonElement);
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
}
}.nullSafe();

View File

@@ -97,15 +97,15 @@
/// Initializes a new instance of the <see cref="{{classname}}" /> class.
/// </summary>
[JsonConstructorAttribute]
{{^isAdditionalPropertiesTrue}}
{{^isAdditionalPropertiesEnabled}}
protected {{classname}}() { }
{{/isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{#isAdditionalPropertiesEnabled}}
protected {{classname}}()
{
this.AdditionalProperties = new Dictionary<string, object>();
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{/hasOnlyReadOnly}}
{{/hasRequired}}
/// <summary>
@@ -170,9 +170,9 @@
{{/isReadOnly}}
{{/isInherited}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
this.AdditionalProperties = new Dictionary<string, object>();
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
}
{{#vars}}
@@ -250,14 +250,14 @@
{{/isEnum}}
{{/isInherited}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
/// <summary>
/// Gets or Sets additional properties
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalProperties { get; set; }
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
@@ -272,9 +272,9 @@
{{#vars}}
sb.Append(" {{name}}: ").Append({{name}}).Append("\n");
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n");
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
sb.Append("}\n");
return sb.ToString();
}
@@ -333,10 +333,10 @@
{{^vendorExtensions.x-is-value-type}}this.{{name}} != null &&
input.{{name}} != null &&
{{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}})
){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesTrue}}
){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesEnabled}};{{/isAdditionalPropertiesEnabled}}
{{#isAdditionalPropertiesEnabled}}
&& (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any());
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{/useCompareNetObjects}}
}
@@ -363,10 +363,10 @@
hashCode = hashCode * 59 + this.{{name}}.GetHashCode();
{{/vendorExtensions.x-is-value-type}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
if (this.AdditionalProperties != null)
hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode();
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
return hashCode;
}
}

View File

@@ -168,7 +168,7 @@
{{/isInherited}}
{{/isEnum}}
{{/allVars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
{{^parentModel}}
/// <summary>
/// Gets or Sets additional properties
@@ -177,7 +177,7 @@
public Dictionary<string, JsonElement> AdditionalProperties { get; } = new Dictionary<string, JsonElement>();
{{/parentModel}}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
@@ -192,11 +192,11 @@
{{#vars}}
sb.Append(" {{name}}: ").Append({{name}}).Append("\n");
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
{{^parentModel}}
sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n");
{{/parentModel}}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
sb.Append("}\n");
return sb.ToString();
}
@@ -249,12 +249,12 @@
{{^vendorExtensions.x-is-value-type}}{{name}} != null &&
input.{{name}} != null &&
{{/vendorExtensions.x-is-value-type}}{{name}}.SequenceEqual(input.{{name}})
){{^-last}} && {{/-last}}{{/isContainer}}{{/isInherited}}{{/readOnlyVars}}{{^readOnlyVars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/readOnlyVars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesTrue}}
){{^-last}} && {{/-last}}{{/isContainer}}{{/isInherited}}{{/readOnlyVars}}{{^readOnlyVars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/readOnlyVars}}{{^isAdditionalPropertiesEnabled}};{{/isAdditionalPropertiesEnabled}}
{{#isAdditionalPropertiesEnabled}}
{{^parentModel}}
&& (AdditionalProperties.Count == input.AdditionalProperties.Count && !AdditionalProperties.Except(input.AdditionalProperties).Any());
{{/parentModel}}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{/useCompareNetObjects}}
}
@@ -284,11 +284,11 @@
hashCode = (hashCode * 59) + {{name}}.GetHashCode();
{{/isNullable}}
{{/readOnlyVars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
{{^parentModel}}
hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode();
{{/parentModel}}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
return hashCode;
}

View File

@@ -114,15 +114,15 @@
/// Initializes a new instance of the <see cref="{{classname}}" /> class.
/// </summary>
[JsonConstructorAttribute]
{{^isAdditionalPropertiesTrue}}
{{^isAdditionalPropertiesEnabled}}
protected {{classname}}() { }
{{/isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{#isAdditionalPropertiesEnabled}}
protected {{classname}}()
{
this.AdditionalProperties = new Dictionary<string, object>();
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{/hasOnlyReadOnly}}
{{/hasRequired}}
/// <summary>
@@ -201,9 +201,9 @@
{{/isReadOnly}}
{{/isInherited}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
this.AdditionalProperties = new Dictionary<string, object>();
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
}
{{#vars}}
@@ -290,14 +290,14 @@
{{/isEnum}}
{{/isInherited}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
/// <summary>
/// Gets or Sets additional properties
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalProperties { get; set; }
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
@@ -312,9 +312,9 @@
{{#vars}}
sb.Append(" {{name}}: ").Append({{name}}).Append("\n");
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n");
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
sb.Append("}\n");
return sb.ToString();
}
@@ -375,10 +375,10 @@
{{^vendorExtensions.x-is-value-type}}this.{{name}} != null &&
input.{{name}} != null &&
{{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}})
){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesTrue}}
){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesEnabled}};{{/isAdditionalPropertiesEnabled}}
{{#isAdditionalPropertiesEnabled}}
&& (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any());
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{/useCompareNetObjects}}
}
@@ -407,12 +407,12 @@
hashCode = (hashCode * 59) + this.{{name}}.GetHashCode();
{{/vendorExtensions.x-is-value-type}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
if (this.AdditionalProperties != null)
{
hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode();
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
return hashCode;
}
}

View File

@@ -400,9 +400,9 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{#isBodyParam}}
{{paramName}}Param := {{dataType}}{}
d := json.NewDecoder(r.Body)
{{^isAdditionalPropertiesTrue}}
{{^isAdditionalPropertiesEnabled}}
d.DisallowUnknownFields()
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
if err := d.Decode(&{{paramName}}Param); err != nil {
c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return

View File

@@ -609,7 +609,11 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e
} else if jsonCheck.MatchString(contentType) {
err = json.NewEncoder(bodyBuf).Encode(body)
} else if xmlCheck.MatchString(contentType) {
err = xml.NewEncoder(bodyBuf).Encode(body)
var bs []byte
bs, err = xml.Marshal(body)
if err == nil {
bodyBuf.Write(bs)
}
}
if err != nil {

View File

@@ -24,15 +24,15 @@ type {{classname}} struct {
{{/deprecated}}
{{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
AdditionalProperties map[string]interface{}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
type _{{{classname}}} {{{classname}}}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
// New{{classname}} instantiates a new {{classname}} object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
@@ -321,17 +321,17 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) {
{{/required}}
{{/isNullable}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
return toSerialize, nil
}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) {
{{#parent}}
{{^isMap}}
@@ -440,7 +440,7 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) {
{{/parent}}
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{#isArray}}
func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) {
return json.Unmarshal(bytes, &o.Items)

View File

@@ -42,14 +42,14 @@ import Data.Function ((&))
} deriving (Show, Eq, Generic, Data)
instance FromJSON {{classname}} where
parseJSON = genericParseJSON (removeFieldLabelPrefix True "{{vendorExtensions.x-prefix}}")
parseJSON = genericParseJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}")
instance ToJSON {{classname}} where
toJSON = genericToJSON (removeFieldLabelPrefix False "{{vendorExtensions.x-prefix}}")
toJSON = genericToJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}")
{{#generateToSchema}}
instance ToSchema {{classname}} where
declareNamedSchema = Swagger.genericDeclareNamedSchema
$ Swagger.fromAesonOptions
$ removeFieldLabelPrefix False "{{vendorExtensions.x-prefix}}"
$ removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}"
{{/generateToSchema}}
{{/parent}}
@@ -70,15 +70,11 @@ uncapitalize [] = []
-- | Remove a field label prefix during JSON parsing.
-- Also perform any replacements for special characters.
-- The @forParsing@ parameter is to distinguish between the cases in which we're using this
-- to power a @FromJSON@ or a @ToJSON@ instance. In the first case we're parsing, and we want
-- to replace special characters with their quoted equivalents (because we cannot have special
-- chars in identifier names), while we want to do vice versa when sending data instead.
removeFieldLabelPrefix :: Bool -> String -> Options
removeFieldLabelPrefix forParsing prefix =
removeFieldLabelPrefix :: String -> Options
removeFieldLabelPrefix prefix =
defaultOptions
{ omitNothingFields = True
, fieldLabelModifier = uncapitalize . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix . replaceSpecialChars
, fieldLabelModifier = uncapitalize . replaceSpecialChars . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix
}
where
replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars)
@@ -86,8 +82,4 @@ removeFieldLabelPrefix forParsing prefix =
[ {{#specialCharReplacements}}("{{&char}}", "{{&replacement}}"){{^-last}}
, {{/-last}}{{/specialCharReplacements}}
]
mkCharReplacement (replaceStr, searchStr) = T.unpack . replacer (T.pack searchStr) (T.pack replaceStr) . T.pack
replacer =
if forParsing
then flip T.replace
else T.replace
mkCharReplacement (replaceStr, searchStr) = T.unpack . T.replace (T.pack searchStr) (T.pack replaceStr) . T.pack

View File

@@ -36,9 +36,9 @@ import Data.Function ((&))
} deriving (Show, Eq, Generic)
instance FromJSON {{classname}} where
parseJSON = genericParseJSON (removeFieldLabelPrefix True "{{vendorExtensions.x-prefix}}")
parseJSON = genericParseJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}")
instance ToJSON {{classname}} where
toJSON = genericToJSON (removeFieldLabelPrefix False "{{vendorExtensions.x-prefix}}")
toJSON = genericToJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}")
{{/parent}}
{{#parent}}
@@ -58,15 +58,11 @@ uncapitalize [] = []
-- | Remove a field label prefix during JSON parsing.
-- Also perform any replacements for special characters.
-- The @forParsing@ parameter is to distinguish between the cases in which we're using this
-- to power a @FromJSON@ or a @ToJSON@ instance. In the first case we're parsing, and we want
-- to replace special characters with their quoted equivalents (because we cannot have special
-- chars in identifier names), while we want to do vice versa when sending data instead.
removeFieldLabelPrefix :: Bool -> String -> Options
removeFieldLabelPrefix forParsing prefix =
removeFieldLabelPrefix :: String -> Options
removeFieldLabelPrefix prefix =
defaultOptions
{ omitNothingFields = True
, fieldLabelModifier = uncapitalize . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix . replaceSpecialChars
, fieldLabelModifier = uncapitalize . replaceSpecialChars . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix
}
where
replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars)
@@ -74,8 +70,4 @@ removeFieldLabelPrefix forParsing prefix =
[ {{#specialCharReplacements}}("{{&char}}", "{{&replacement}}"){{^-last}}
, {{/-last}}{{/specialCharReplacements}}
]
mkCharReplacement (replaceStr, searchStr) = T.unpack . replacer (T.pack searchStr) (T.pack replaceStr) . T.pack
replacer =
if forParsing
then flip T.replace
else T.replace
mkCharReplacement (replaceStr, searchStr) = T.unpack . T.replace (T.pack searchStr) (T.pack replaceStr) . T.pack

View File

@@ -223,24 +223,24 @@ function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} {
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
${{{apiNamePrefix}}}{{{classname}}}AdditionalProperties = @{}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
# check if Json contains properties not defined in {{{apiNamePrefix}}}{{{classname}}}
$AllProperties = ({{#allVars}}"{{{baseName}}}"{{^-last}}, {{/-last}}{{/allVars}})
foreach ($name in $JsonParameters.PsObject.Properties.Name) {
{{^isAdditionalPropertiesTrue}}
{{^isAdditionalPropertiesEnabled}}
if (!($AllProperties.Contains($name))) {
throw "Error! JSON key '$name' not found in the properties: $($AllProperties)"
}
{{/isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{#isAdditionalPropertiesEnabled}}
# store undefined properties in additionalProperties
if (!($AllProperties.Contains($name))) {
${{{apiNamePrefix}}}{{{classname}}}AdditionalProperties[$name] = $JsonParameters.PSobject.Properties[$name].value
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
}
{{#requiredVars}}
@@ -271,9 +271,9 @@ function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} {
"<<baseName>>" = ${<<name>>}
<</allVars>>
<<={{ }}=>>
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
"AdditionalProperties" = ${{{apiNamePrefix}}}{{{classname}}}AdditionalProperties
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
}
return $PSO

View File

@@ -29,3 +29,10 @@ from pprint import pprint
except Exception as e:
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
```
{{#vendorExtensions.x-py-postponed-example-imports.size}}
{{#vendorExtensions.x-py-postponed-example-imports}}
{{{.}}}
{{/vendorExtensions.x-py-postponed-example-imports}}
{{classname}}.update_forward_refs()
{{/vendorExtensions.x-py-postponed-example-imports.size}}

View File

@@ -9,7 +9,7 @@ import re # noqa: F401
{{#vendorExtensions.x-py-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-model-imports}}
from typing import Any, List
from typing import Union, Any, List, TYPE_CHECKING
from pydantic import StrictStr, Field
{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}]
@@ -23,7 +23,10 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
# data type: {{{dataType}}}
{{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}}
{{/composedSchemas.anyOf}}
actual_instance: Any
if TYPE_CHECKING:
actual_instance: Union[{{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}]
else:
actual_instance: Any
any_of_schemas: List[str] = Field({{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS, const=True)
class Config:
@@ -168,3 +171,10 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
def to_str(self) -> str:
"""Returns the string representation of the actual instance"""
return pprint.pformat(self.dict())
{{#vendorExtensions.x-py-postponed-model-imports.size}}
{{#vendorExtensions.x-py-postponed-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-postponed-model-imports}}
{{classname}}.update_forward_refs()
{{/vendorExtensions.x-py-postponed-model-imports.size}}

View File

@@ -22,9 +22,9 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{#vars}}
{{name}}: {{{vendorExtensions.x-py-typing}}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
additional_properties: Dict[str, Any] = {}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
__properties = [{{#allVars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/allVars}}]
{{#vars}}
{{#vendorExtensions.x-regex}}
@@ -130,9 +130,9 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{#vendorExtensions.x-py-readonly}}
"{{{.}}}",
{{/vendorExtensions.x-py-readonly}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
"additional_properties"
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
},
exclude_none=True)
{{#allVars}}
@@ -202,13 +202,13 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/isPrimitiveType}}
{{/isContainer}}
{{/allVars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
# puts key-value pairs in additional_properties in the top level
if self.additional_properties is not None:
for _key, _value in self.additional_properties.items():
_dict[_key] = _value
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{#allVars}}
{{#isNullable}}
# set to None if {{{name}}} (nullable) is None
@@ -244,13 +244,13 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return {{{classname}}}.parse_obj(obj)
{{#disallowAdditionalPropertiesIfNotPresent}}
{{^isAdditionalPropertiesTrue}}
{{^isAdditionalPropertiesEnabled}}
# raise errors for additional fields in the input
for _key in obj.keys():
if _key not in cls.__properties:
raise ValueError("Error due to additional fields (not defined in {{classname}}) in the input: " + obj)
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{/disallowAdditionalPropertiesIfNotPresent}}
_obj = {{{classname}}}.parse_obj({
{{#allVars}}
@@ -348,12 +348,19 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/isContainer}}
{{/allVars}}
})
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
# store additional fields in additional_properties
for _key in obj.keys():
if _key not in cls.__properties:
_obj.additional_properties[_key] = obj.get(_key)
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
return _obj
{{/hasChildren}}
{{#vendorExtensions.x-py-postponed-model-imports.size}}
{{#vendorExtensions.x-py-postponed-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-postponed-model-imports}}
{{classname}}.update_forward_refs()
{{/vendorExtensions.x-py-postponed-model-imports.size}}

View File

@@ -9,7 +9,7 @@ import re # noqa: F401
{{#vendorExtensions.x-py-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-model-imports}}
from typing import Any, List
from typing import Union, Any, List, TYPE_CHECKING
from pydantic import StrictStr, Field
{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS = [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}]
@@ -22,7 +22,10 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
# data type: {{{dataType}}}
{{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}}
{{/composedSchemas.oneOf}}
actual_instance: Any
if TYPE_CHECKING:
actual_instance: Union[{{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}]
else:
actual_instance: Any
one_of_schemas: List[str] = Field({{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS, const=True)
class Config:
@@ -194,3 +197,10 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
def to_str(self) -> str:
"""Returns the string representation of the actual instance"""
return pprint.pformat(self.dict())
{{#vendorExtensions.x-py-postponed-model-imports.size}}
{{#vendorExtensions.x-py-postponed-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-postponed-model-imports}}
{{classname}}.update_forward_refs()
{{/vendorExtensions.x-py-postponed-model-imports.size}}

View File

@@ -10,10 +10,10 @@
{{#vars}}
#' @field {{name}} {{#lambdaRdocEscape}}{{{description}}}{{/lambdaRdocEscape}} {{{vendorExtensions.x-r-doc-type}}}{{^required}} [optional]{{/required}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
#' @field _field_list a list of fields list(character)
#' @field additional_properties additional properties list(character) [optional]
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
#' @importFrom R6 R6Class
#' @importFrom jsonlite fromJSON toJSON
#' @export
@@ -26,10 +26,10 @@
{{#vars}}
`{{{name}}}` = NULL,
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
`_field_list` = c({{#vars}}"{{{name}}}"{{^-last}}, {{/-last}}{{/vars}}),
`additional_properties` = list(),
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{#discriminator}}
`_discriminator_property_name` = '{{discriminator.propertyName}}',
{{#discriminator.mappedModels}}{{#-first}}`_discriminator_mapping_name` = c({{/-first}}'{{mappingName}}' = '{{modelName}}'{{^-last}}, {{/-last}}{{#-last}}),{{/-last}}{{/discriminator.mappedModels}}
@@ -45,12 +45,12 @@
{{#optionalVars}}
#' @param {{name}} {{#lambdaRdocEscape}}{{{description}}}{{/lambdaRdocEscape}}{{^description}}{{{name}}}{{/description}}{{#defaultValue}}. Default to {{{.}}}.{{/defaultValue}}
{{/optionalVars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
#' @param additional_properties additional properties (optional)
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
#' @param ... Other optional arguments.
#' @export
initialize = function({{#requiredVars}}`{{name}}`, {{/requiredVars}}{{#optionalVars}}`{{name}}` = {{{defaultValue}}}{{^defaultValue}}NULL{{/defaultValue}}, {{/optionalVars}}{{#isAdditionalPropertiesTrue}}additional_properties = NULL, {{/isAdditionalPropertiesTrue}}...) {
initialize = function({{#requiredVars}}`{{name}}`, {{/requiredVars}}{{#optionalVars}}`{{name}}` = {{{defaultValue}}}{{^defaultValue}}NULL{{/defaultValue}}, {{/optionalVars}}{{#isAdditionalPropertiesEnabled}}additional_properties = NULL, {{/isAdditionalPropertiesEnabled}}...) {
{{#requiredVars}}
if (!missing(`{{name}}`)) {
{{^isContainer}}
@@ -195,13 +195,13 @@
self$`{{name}}` <- `{{name}}`
}
{{/optionalVars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
if (!is.null(additional_properties)) {
for (key in names(additional_properties)) {
self$additional_properties[[key]] <- additional_properties[[key]]
}
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
},
#' To JSON string
#'
@@ -243,12 +243,12 @@
{{/isContainer}}
}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
for (key in names(self$additional_properties)) {
{{classname}}Object[[key]] <- self$additional_properties[[key]]
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
{{classname}}Object
},
#' Deserialize JSON string into an instance of {{{classname}}}
@@ -296,7 +296,7 @@
{{/isContainer}}
}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
# process additional properties/fields in the payload
for (key in names(this_object)) {
if (!(key %in% self$`_field_list`)) { # json key not in list of fields
@@ -304,7 +304,7 @@
}
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
self
},
#' To JSON string
@@ -375,13 +375,13 @@
)
jsoncontent <- paste(jsoncontent, collapse = ",")
json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = "")))
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
json_obj <- jsonlite::fromJSON(json_string)
for (key in names(self$additional_properties)) {
json_obj[[key]] <- self$additional_properties[[key]]
}
json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA)))
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
},
#' Deserialize JSON string into an instance of {{{classname}}}
#'
@@ -425,7 +425,7 @@
{{/isPrimitiveType}}
{{/isContainer}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
{{#isAdditionalPropertiesEnabled}}
# process additional properties/fields in the payload
for (key in names(this_object)) {
if (!(key %in% self$`_field_list`)) { # json key not in list of fields
@@ -433,7 +433,7 @@
}
}
{{/isAdditionalPropertiesTrue}}
{{/isAdditionalPropertiesEnabled}}
self
},
#' Validate JSON input with respect to {{classname}}

View File

@@ -0,0 +1,786 @@
openapi: 3.0.0
servers:
- url: 'http://petstore.swagger.io/v2'
info:
description: >-
This is a sample server Petstore server. For this sample, you can use the api key
`special-key` to test the authorization filters.
version: 1.0.0
title: OpenAPI Petstore
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: pet
description: Everything about your Pets
- name: store
description: Access to Petstore orders
- name: user
description: Operations about user
paths:
/pet:
post:
tags:
- pet
summary: Add a new pet to the store
description: ''
operationId: addPet
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
'405':
description: Invalid input
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
$ref: '#/components/requestBodies/Pet'
put:
tags:
- pet
summary: Update an existing pet
description: ''
operationId: updatePet
externalDocs:
url: "http://petstore.swagger.io/v2/doc/updatePet"
description: "API documentation for the updatePet operation"
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid ID supplied
'404':
description: Pet not found
'405':
description: Validation exception
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
$ref: '#/components/requestBodies/Pet'
/pet/findByStatus:
get:
tags:
- pet
summary: Finds Pets by status
description: Multiple status values can be provided with comma separated strings
operationId: findPetsByStatus
parameters:
- name: status
in: query
description: Status values that need to be considered for filter
required: true
style: form
explode: false
deprecated: true
schema:
type: array
items:
type: string
enum:
- available
- pending
- sold
default: available
responses:
'200':
description: successful operation
content:
application/xml:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid status value
security:
- petstore_auth:
- 'read:pets'
/pet/findByTags:
get:
tags:
- pet
summary: Finds Pets by tags
description: >-
Multiple tags can be provided with comma separated strings. Use tag1,
tag2, tag3 for testing.
operationId: findPetsByTags
parameters:
- name: tags
in: query
description: Tags to filter by
required: true
style: form
explode: false
schema:
type: array
items:
type: string
responses:
'200':
description: successful operation
content:
application/xml:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid tag value
security:
- petstore_auth:
- 'read:pets'
deprecated: true
'/pet/{petId}':
get:
tags:
- pet
summary: Find pet by ID
description: Returns a single pet
operationId: getPetById
parameters:
- name: petId
in: path
description: ID of pet to return
required: true
schema:
type: integer
format: int64
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid ID supplied
'404':
description: Pet not found
security:
- api_key: []
post:
tags:
- pet
summary: Updates a pet in the store with form data
description: ''
operationId: updatePetWithForm
parameters:
- name: petId
in: path
description: ID of pet that needs to be updated
required: true
schema:
type: integer
format: int64
responses:
'405':
description: Invalid input
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
name:
description: Updated name of the pet
type: string
status:
description: Updated status of the pet
type: string
delete:
tags:
- pet
summary: Deletes a pet
description: ''
operationId: deletePet
parameters:
- name: api_key
in: header
required: false
schema:
type: string
- name: petId
in: path
description: Pet id to delete
required: true
schema:
type: integer
format: int64
responses:
'400':
description: Invalid pet value
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
'/pet/{petId}/uploadImage':
post:
tags:
- pet
summary: uploads an image
description: ''
operationId: uploadFile
parameters:
- name: petId
in: path
description: ID of pet to update
required: true
schema:
type: integer
format: int64
responses:
'200':
description: successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
additionalMetadata:
description: Additional data to pass to server
type: string
file:
description: file to upload
type: string
format: binary
/store/inventory:
get:
tags:
- store
summary: Returns pet inventories by status
description: Returns a map of status codes to quantities
operationId: getInventory
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
additionalProperties:
type: integer
format: int32
security:
- api_key: []
/store/order:
post:
tags:
- store
summary: Place an order for a pet
description: ''
operationId: placeOrder
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
'400':
description: Invalid Order
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
description: order placed for purchasing the pet
required: true
'/store/order/{orderId}':
get:
tags:
- store
summary: Find purchase order by ID
description: >-
For valid response try integer IDs with value <= 5 or > 10. Other values
will generate exceptions
operationId: getOrderById
parameters:
- name: orderId
in: path
description: ID of pet that needs to be fetched
required: true
schema:
type: integer
format: int64
minimum: 1
maximum: 5
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
'400':
description: Invalid ID supplied
'404':
description: Order not found
delete:
tags:
- store
summary: Delete purchase order by ID
description: >-
For valid response try integer IDs with value < 1000. Anything above
1000 or nonintegers will generate API errors
operationId: deleteOrder
parameters:
- name: orderId
in: path
description: ID of the order that needs to be deleted
required: true
schema:
type: string
responses:
'400':
description: Invalid ID supplied
'404':
description: Order not found
/user:
post:
tags:
- user
summary: Create user
description: This can only be done by the logged in user.
operationId: createUser
responses:
default:
description: successful operation
security:
- api_key: []
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Created user object
required: true
/user/createWithArray:
post:
tags:
- user
summary: Creates list of users with given input array
description: ''
operationId: createUsersWithArrayInput
responses:
default:
description: successful operation
security:
- api_key: []
requestBody:
$ref: '#/components/requestBodies/UserArray'
/user/createWithList:
post:
tags:
- user
summary: Creates list of users with given input array
description: ''
operationId: createUsersWithListInput
responses:
default:
description: successful operation
security:
- api_key: []
requestBody:
$ref: '#/components/requestBodies/UserArray'
/user/login:
get:
tags:
- user
summary: Logs user into the system
description: ''
operationId: loginUser
parameters:
- name: username
in: query
description: The user name for login
required: true
schema:
type: string
pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
- name: password
in: query
description: The password for login in clear text
required: true
schema:
type: string
responses:
'200':
description: successful operation
headers:
Set-Cookie:
description: >-
Cookie authentication key for use with the `api_key`
apiKey authentication.
schema:
type: string
example: AUTH_KEY=abcde12345; Path=/; HttpOnly
X-Rate-Limit:
description: calls per hour allowed by the user
schema:
type: integer
format: int32
X-Expires-After:
description: date in UTC when token expires
schema:
type: string
format: date-time
content:
application/xml:
schema:
type: string
application/json:
schema:
type: string
'400':
description: Invalid username/password supplied
/user/logout:
get:
tags:
- user
summary: Logs out current logged in user session
description: ''
operationId: logoutUser
responses:
default:
description: successful operation
security:
- api_key: []
'/user/{username}':
get:
tags:
- user
summary: Get user by user name
description: ''
operationId: getUserByName
parameters:
- name: username
in: path
description: The name that needs to be fetched. Use user1 for testing.
required: true
schema:
type: string
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/User'
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid username supplied
'404':
description: User not found
put:
tags:
- user
summary: Updated user
description: This can only be done by the logged in user.
operationId: updateUser
parameters:
- name: username
in: path
description: name that need to be deleted
required: true
schema:
type: string
responses:
'400':
description: Invalid user supplied
'404':
description: User not found
security:
- api_key: []
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Updated user object
required: true
delete:
tags:
- user
summary: Delete user
description: This can only be done by the logged in user.
operationId: deleteUser
parameters:
- name: username
in: path
description: The name that needs to be deleted
required: true
schema:
type: string
responses:
'400':
description: Invalid username supplied
'404':
description: User not found
security:
- api_key: []
/fake/parameter-name-mapping:
get:
tags:
- fake
summary: parameter name mapping test
operationId: getParameterNameMapping
parameters:
- name: _type
in: header
description: _type
required: true
schema:
type: integer
format: int64
- name: type
in: query
description: type
required: true
schema:
type: string
- name: type_
in: header
description: type_
required: true
schema:
type: string
- name: http_debug_option
in: query
description: http debug option (to test parameter naming option)
required: true
schema:
type: string
responses:
200:
description: OK
externalDocs:
description: Find out more about Swagger
url: 'http://swagger.io'
components:
requestBodies:
UserArray:
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
description: List of user object
required: true
Pet:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
description: Pet object that needs to be added to the store
required: true
securitySchemes:
petstore_auth:
type: oauth2
flows:
implicit:
authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog'
scopes:
'write:pets': modify pets in your account
'read:pets': read your pets
api_key:
type: apiKey
name: api_key
in: header
schemas:
Order:
title: Pet Order
description: An order for a pets from the pet store
type: object
properties:
id:
type: integer
format: int64
petId:
type: integer
format: int64
quantity:
type: integer
format: int32
shipDate:
type: string
format: date-time
status:
type: string
description: Order Status
enum:
- placed
- approved
- delivered
complete:
type: boolean
default: false
xml:
name: Order
Category:
title: Pet category
description: A category for a pet
type: object
properties:
id:
type: integer
format: int64
name:
type: string
pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
xml:
name: Category
User:
title: a User
description: A User who is purchasing from the pet store
type: object
properties:
id:
type: integer
format: int64
username:
type: string
firstName:
type: string
lastName:
type: string
email:
type: string
password:
type: string
phone:
type: string
userStatus:
type: integer
format: int32
description: User Status
xml:
name: User
Tag:
title: Pet Tag
description: A tag for a pet
type: object
properties:
id:
type: integer
format: int64
name:
type: string
xml:
name: Tag
Pet:
title: a Pet
description: A pet for sale in the pet store
type: object
required:
- name
- photoUrls
properties:
id:
type: integer
format: int64
category:
$ref: '#/components/schemas/Category'
name:
type: string
example: doggie
photoUrls:
type: array
xml:
name: photoUrl
wrapped: true
items:
type: string
tags:
type: array
xml:
name: tag
wrapped: true
items:
$ref: '#/components/schemas/Tag'
status:
type: string
description: pet status in the store
deprecated: true
enum:
- available
- pending
- sold
xml:
name: Pet
ApiResponse:
title: An uploaded response
description: Describes the result of uploading an image resource
type: object
properties:
code:
type: integer
format: int32
type:
type: string
message:
type: string
PropertyNameMapping:
properties:
http_debug_operation:
type: string
_type:
type: string
type:
type: string
type_:
type: string

View File

@@ -1178,6 +1178,41 @@ paths:
responses:
'200':
description: OK
/fake/parameter-name-mapping:
get:
tags:
- fake
summary: parameter name mapping test
operationId: getParameterNameMapping
parameters:
- name: _type
in: header
description: _type
required: true
schema:
type: integer
format: int64
- name: type
in: query
description: type
required: true
schema:
type: string
- name: type_
in: header
description: type_
required: true
schema:
type: string
- name: http_debug_option
in: query
description: http debug option (to test parameter naming option)
required: true
schema:
type: string
responses:
200:
description: OK
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
@@ -2058,3 +2093,13 @@ components:
test:
type: string
format: date-time
PropertyNameMapping:
properties:
http_debug_operation:
type: string
_type:
type: string
type:
type: string
type_:
type: string

View File

@@ -0,0 +1,56 @@
openapi: 3.0.0
info:
description: To test name, parameter mapping options
version: 1.0.0
title: Dummy
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
paths:
/fake/parameter-name-mapping:
get:
tags:
- fake
summary: parameter name mapping test
operationId: getParameterNameMapping
parameters:
- name: _type
in: header
description: _type
required: true
schema:
type: integer
format: int64
- name: type
in: query
description: type
required: true
schema:
type: string
- name: type_
in: header
description: type_
required: true
schema:
type: string
- name: http_debug_option
in: query
description: http debug option (to test parameter naming option)
required: true
schema:
type: string
responses:
200:
description: OK
components:
schemas:
PropertyNameMapping:
properties:
http_debug_operation:
type: string
_type:
type: string
type:
type: string
type_:
type: string

View File

@@ -2238,3 +2238,24 @@ components:
type_:
type: string
type: object
ObjectToTestAdditionalProperties:
description: Minimal object
type: object
properties:
property:
description: Property
type: boolean
default: false
AdditionalPropertieObject:
type: object
properties:
name:
type: string
additionalProperties:
type: object
AdditionalPropertieAnyType:
type: object
properties:
name:
type: string
additionalProperties: {}

View File

@@ -1267,6 +1267,41 @@ paths:
responses:
200:
description: The instance started successfully
/fake/parameter-name-mapping:
get:
tags:
- fake
summary: parameter name mapping test
operationId: getParameterNameMapping
parameters:
- name: _type
in: header
description: _type
required: true
schema:
type: integer
format: int64
- name: type
in: query
description: type
required: true
schema:
type: string
- name: type_
in: header
description: type_
required: true
schema:
type: string
- name: http_debug_option
in: query
description: http debug option (to test parameter naming option)
required: true
schema:
type: string
responses:
200:
description: OK
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
@@ -2045,3 +2080,13 @@ components:
required:
- classname
additionalProperties: true
PropertyNameMapping:
properties:
http_debug_operation:
type: string
_type:
type: string
type:
type: string
type_:
type: string

View File

@@ -566,6 +566,41 @@ paths:
description: User not found
security:
- api_key: []
/fake/parameter-name-mapping:
get:
tags:
- fake
summary: parameter name mapping test
operationId: getParameterNameMapping
parameters:
- name: _type
in: header
description: _type
required: true
schema:
type: integer
format: int64
- name: type
in: query
description: type
required: true
schema:
type: string
- name: type_
in: header
description: type_
required: true
schema:
type: string
- name: http_debug_option
in: query
description: http debug option (to test parameter naming option)
required: true
schema:
type: string
responses:
200:
description: OK
externalDocs:
description: Find out more about Swagger
url: 'http://swagger.io'
@@ -758,3 +793,13 @@ components:
type: string
type: array
type: object
PropertyNameMapping:
properties:
http_debug_operation:
type: string
_type:
type: string
type:
type: string
type_:
type: string

View File

@@ -1166,12 +1166,15 @@ public class ApiClient {
// prepare HTTP request body
RequestBody reqBody;
String contentType = headerParams.get("Content-Type");
String contentTypePure = contentType;
if (contentTypePure != null && contentTypePure.contains(";")) {
contentTypePure = contentType.substring(0, contentType.indexOf(";"));
}
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
} else if ("application/x-www-form-urlencoded".equals(contentTypePure)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentType)) {
} else if ("multipart/form-data".equals(contentTypePure)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {

View File

@@ -51,6 +51,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
This endpoint does not need any parameter.
@@ -113,6 +114,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -178,6 +180,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -243,6 +246,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -309,6 +313,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -375,6 +380,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -441,6 +447,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes

View File

@@ -48,6 +48,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes

View File

@@ -48,6 +48,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes

View File

@@ -47,6 +47,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes

View File

@@ -54,6 +54,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -121,6 +122,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -190,6 +192,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -258,6 +261,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -323,6 +327,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -389,6 +394,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -455,6 +461,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes
@@ -520,6 +527,7 @@ with openapi_client.ApiClient(configuration) as api_client:
```
### Parameters
Name | Type | Description | Notes

View File

@@ -71,3 +71,4 @@ class Bird(BaseModel):
})
return _obj

View File

@@ -71,3 +71,4 @@ class Category(BaseModel):
})
return _obj

View File

@@ -20,7 +20,7 @@ import json
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field, StrictStr
from pydantic import Field, StrictStr
from openapi_client.models.query import Query
class DataQuery(Query):
@@ -76,3 +76,4 @@ class DataQuery(Query):
})
return _obj

View File

@@ -110,3 +110,4 @@ class DefaultValue(BaseModel):
})
return _obj

View File

@@ -73,3 +73,4 @@ class NumberPropertiesOnly(BaseModel):
})
return _obj

View File

@@ -101,3 +101,4 @@ class Pet(BaseModel):
})
return _obj

View File

@@ -71,3 +71,4 @@ class Query(BaseModel):
def from_dict(cls, obj: dict) -> Query:
"""Create an instance of Query from a dict"""

View File

@@ -71,3 +71,4 @@ class Tag(BaseModel):
})
return _obj

View File

@@ -75,3 +75,4 @@ class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseMod
})
return _obj

View File

@@ -69,3 +69,4 @@ class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(BaseModel):
})
return _obj

View File

@@ -1189,12 +1189,15 @@ public class ApiClient {
// prepare HTTP request body
RequestBody reqBody;
String contentType = headerParams.get("Content-Type");
String contentTypePure = contentType;
if (contentTypePure != null && contentTypePure.contains(";")) {
contentTypePure = contentType.substring(0, contentType.indexOf(";"));
}
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
} else if ("application/x-www-form-urlencoded".equals(contentTypePure)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentType)) {
} else if ("multipart/form-data".equals(contentTypePure)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {

View File

@@ -26,18 +26,39 @@ package body Samples.Petstore.Clients is
1 => Mime_1'Access );
-- parameter name mapping test
procedure Get_Parameter_Name_Mapping
(Client : in out Client_Type;
UnderscoreType : in Swagger.Long;
P_Type : in Swagger.UString;
TypeWithUnderscore : in Swagger.UString;
Http_Debug_Option : in Swagger.UString) is
URI : Swagger.Clients.URI_Type;
begin
URI.Add_Param ("type", P_Type);
URI.Add_Param ("http_debug_option", Http_Debug_Option);
URI.Set_Path ("/fake/parameter-name-mapping");
Client.Call (Swagger.Clients.GET, URI);
end Get_Parameter_Name_Mapping;
-- Add a new pet to the store
procedure Add_Pet
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.Pet_Type) is
Pet_Type : in Samples.Petstore.Models.Pet_Type;
Result : out Samples.Petstore.Models.Pet_Type) is
URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type;
Reply : Swagger.Value_Type;
begin
Client.Set_Accept (Media_List_1);
Client.Initialize (Req, Media_List_1);
Samples.Petstore.Models.Serialize (Req.Stream, "", P_Body);
Samples.Petstore.Models.Serialize (Req.Stream, "", Pet_Type);
URI.Set_Path ("/pet");
Client.Call (Swagger.Clients.POST, URI, Req);
Client.Call (Swagger.Clients.POST, URI, Req, Reply);
Samples.Petstore.Models.Deserialize (Reply, "", Result);
end Add_Pet;
-- Deletes a pet
@@ -111,15 +132,19 @@ package body Samples.Petstore.Clients is
-- Update an existing pet
procedure Update_Pet
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.Pet_Type) is
Pet_Type : in Samples.Petstore.Models.Pet_Type;
Result : out Samples.Petstore.Models.Pet_Type) is
URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type;
Reply : Swagger.Value_Type;
begin
Client.Set_Accept (Media_List_1);
Client.Initialize (Req, Media_List_1);
Samples.Petstore.Models.Serialize (Req.Stream, "", P_Body);
Samples.Petstore.Models.Serialize (Req.Stream, "", Pet_Type);
URI.Set_Path ("/pet");
Client.Call (Swagger.Clients.PUT, URI, Req);
Client.Call (Swagger.Clients.PUT, URI, Req, Reply);
Samples.Petstore.Models.Deserialize (Reply, "", Result);
end Update_Pet;
-- Updates a pet in the store with form data
@@ -156,7 +181,7 @@ package body Samples.Petstore.Clients is
Client.Initialize (Req, Media_List_4);
Req.Stream.Write_Entity ("additionalMetadata", Additional_Metadata);
-- Req.Stream.Write_Entity ("file", File);
Req.Stream.Write_Entity ("file", File);
URI.Set_Path ("/pet/{petId}/uploadImage");
URI.Set_Path_Param ("petId", Swagger.To_String (Pet_Id));
@@ -215,15 +240,15 @@ package body Samples.Petstore.Clients is
-- Place an order for a pet
procedure Place_Order
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.Order_Type;
Order_Type : in Samples.Petstore.Models.Order_Type;
Result : out Samples.Petstore.Models.Order_Type) is
URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type;
Reply : Swagger.Value_Type;
begin
Client.Set_Accept (Media_List_1);
Client.Initialize (Req);
Samples.Petstore.Models.Serialize (Req.Stream, "", P_Body);
Client.Initialize (Req, Media_List_2);
Samples.Petstore.Models.Serialize (Req.Stream, "", Order_Type);
URI.Set_Path ("/store/order");
Client.Call (Swagger.Clients.POST, URI, Req, Reply);
@@ -234,12 +259,12 @@ package body Samples.Petstore.Clients is
-- This can only be done by the logged in user.
procedure Create_User
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.User_Type) is
User_Type : in Samples.Petstore.Models.User_Type) is
URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type;
begin
Client.Initialize (Req);
Samples.Petstore.Models.Serialize (Req.Stream, "", P_Body);
Client.Initialize (Req, Media_List_2);
Samples.Petstore.Models.Serialize (Req.Stream, "", User_Type);
URI.Set_Path ("/user");
Client.Call (Swagger.Clients.POST, URI, Req);
@@ -248,12 +273,12 @@ package body Samples.Petstore.Clients is
-- Creates list of users with given input array
procedure Create_Users_With_Array_Input
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.User_Type_Vectors.Vector) is
User : in Samples.Petstore.Models.User_Type_Vectors.Vector) is
URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type;
begin
Client.Initialize (Req);
Samples.Petstore.Models.Serialize (Req.Stream, "", P_Body);
Client.Initialize (Req, Media_List_2);
Samples.Petstore.Models.Serialize (Req.Stream, "", User);
URI.Set_Path ("/user/createWithArray");
Client.Call (Swagger.Clients.POST, URI, Req);
@@ -262,12 +287,12 @@ package body Samples.Petstore.Clients is
-- Creates list of users with given input array
procedure Create_Users_With_List_Input
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.User_Type_Vectors.Vector) is
User : in Samples.Petstore.Models.User_Type_Vectors.Vector) is
URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type;
begin
Client.Initialize (Req);
Samples.Petstore.Models.Serialize (Req.Stream, "", P_Body);
Client.Initialize (Req, Media_List_2);
Samples.Petstore.Models.Serialize (Req.Stream, "", User);
URI.Set_Path ("/user/createWithList");
Client.Call (Swagger.Clients.POST, URI, Req);
@@ -339,12 +364,12 @@ package body Samples.Petstore.Clients is
procedure Update_User
(Client : in out Client_Type;
Username : in Swagger.UString;
P_Body : in Samples.Petstore.Models.User_Type) is
User_Type : in Samples.Petstore.Models.User_Type) is
URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type;
begin
Client.Initialize (Req);
Samples.Petstore.Models.Serialize (Req.Stream, "", P_Body);
Client.Initialize (Req, Media_List_2);
Samples.Petstore.Models.Serialize (Req.Stream, "", User_Type);
URI.Set_Path ("/user/{username}");
URI.Set_Path_Param ("username", Username);

View File

@@ -15,10 +15,19 @@ package Samples.Petstore.Clients is
type Client_Type is new Swagger.Clients.Client_Type with null record;
-- parameter name mapping test
procedure Get_Parameter_Name_Mapping
(Client : in out Client_Type;
UnderscoreType : in Swagger.Long;
P_Type : in Swagger.UString;
TypeWithUnderscore : in Swagger.UString;
Http_Debug_Option : in Swagger.UString);
-- Add a new pet to the store
procedure Add_Pet
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.Pet_Type);
Pet_Type : in Samples.Petstore.Models.Pet_Type;
Result : out Samples.Petstore.Models.Pet_Type);
-- Deletes a pet
procedure Delete_Pet
@@ -50,7 +59,8 @@ package Samples.Petstore.Clients is
-- Update an existing pet
procedure Update_Pet
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.Pet_Type);
Pet_Type : in Samples.Petstore.Models.Pet_Type;
Result : out Samples.Petstore.Models.Pet_Type);
-- Updates a pet in the store with form data
procedure Update_Pet_With_Form
@@ -89,24 +99,24 @@ package Samples.Petstore.Clients is
-- Place an order for a pet
procedure Place_Order
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.Order_Type;
Order_Type : in Samples.Petstore.Models.Order_Type;
Result : out Samples.Petstore.Models.Order_Type);
-- Create user
-- This can only be done by the logged in user.
procedure Create_User
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.User_Type);
User_Type : in Samples.Petstore.Models.User_Type);
-- Creates list of users with given input array
procedure Create_Users_With_Array_Input
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.User_Type_Vectors.Vector);
User : in Samples.Petstore.Models.User_Type_Vectors.Vector);
-- Creates list of users with given input array
procedure Create_Users_With_List_Input
(Client : in out Client_Type;
P_Body : in Samples.Petstore.Models.User_Type_Vectors.Vector);
User : in Samples.Petstore.Models.User_Type_Vectors.Vector);
-- Delete user
-- This can only be done by the logged in user.
@@ -136,6 +146,6 @@ package Samples.Petstore.Clients is
procedure Update_User
(Client : in out Client_Type;
Username : in Swagger.UString;
P_Body : in Samples.Petstore.Models.User_Type);
User_Type : in Samples.Petstore.Models.User_Type);
end Samples.Petstore.Clients;

View File

@@ -182,6 +182,63 @@ package body Samples.Petstore.Models is
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in Samples.Petstore.Models.PropertyNameMapping_Type) is
begin
Into.Start_Entity (Name);
if not Value.P_HTTPDebugOperation.Is_Null then
Into.Write_Entity ("http_debug_operation", Value.P_HTTPDebugOperation);
end if;
if not Value.P_UnderscoreType.Is_Null then
Into.Write_Entity ("_type", Value.P_UnderscoreType);
end if;
if not Value.P_Type.Is_Null then
Into.Write_Entity ("type", Value.P_Type);
end if;
if not Value.P_TypeWithUnderscore.Is_Null then
Into.Write_Entity ("type_", Value.P_TypeWithUnderscore);
end if;
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in PropertyNameMapping_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out Samples.Petstore.Models.PropertyNameMapping_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "http_debug_operation", Value.P_HTTPDebugOperation);
Swagger.Streams.Deserialize (Object, "_type", Value.P_UnderscoreType);
Swagger.Streams.Deserialize (Object, "type", Value.P_Type);
Swagger.Streams.Deserialize (Object, "type_", Value.P_TypeWithUnderscore);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : in out PropertyNameMapping_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : Samples.Petstore.Models.PropertyNameMapping_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in Samples.Petstore.Models.Tag_Type) is

View File

@@ -106,6 +106,34 @@ package Samples.Petstore.Models is
Value : in out Order_Type_Vectors.Vector);
type PropertyNameMapping_Type is
record
P_HTTPDebugOperation : Swagger.Nullable_UString;
P_UnderscoreType : Swagger.Nullable_UString;
P_Type : Swagger.Nullable_UString;
P_TypeWithUnderscore : Swagger.Nullable_UString;
end record;
package PropertyNameMapping_Type_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Samples.Petstore.Models.PropertyNameMapping_Type);
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in Samples.Petstore.Models.PropertyNameMapping_Type);
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in PropertyNameMapping_Type_Vectors.Vector);
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out Samples.Petstore.Models.PropertyNameMapping_Type);
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : in out PropertyNameMapping_Type_Vectors.Vector);
-- ------------------------------
-- Pet Tag
-- A tag for a pet

View File

@@ -0,0 +1,362 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

View File

@@ -0,0 +1,23 @@
# 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

View File

@@ -0,0 +1,29 @@
.gitignore
Org.OpenAPITools.sln
README.md
api/openapi.yaml
appveyor.yml
docs/FakeApi.md
docs/PropertyNameMapping.md
git_push.sh
src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj
src/Org.OpenAPITools/Api/FakeApi.cs
src/Org.OpenAPITools/Client/ApiClient.cs
src/Org.OpenAPITools/Client/ApiException.cs
src/Org.OpenAPITools/Client/ApiResponse.cs
src/Org.OpenAPITools/Client/ClientUtils.cs
src/Org.OpenAPITools/Client/Configuration.cs
src/Org.OpenAPITools/Client/ExceptionFactory.cs
src/Org.OpenAPITools/Client/GlobalConfiguration.cs
src/Org.OpenAPITools/Client/HttpMethod.cs
src/Org.OpenAPITools/Client/IApiAccessor.cs
src/Org.OpenAPITools/Client/IAsynchronousClient.cs
src/Org.OpenAPITools/Client/IReadableConfiguration.cs
src/Org.OpenAPITools/Client/ISynchronousClient.cs
src/Org.OpenAPITools/Client/Multimap.cs
src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs
src/Org.OpenAPITools/Client/RequestOptions.cs
src/Org.OpenAPITools/Client/RetryConfiguration.cs
src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs
src/Org.OpenAPITools/Model/PropertyNameMapping.cs
src/Org.OpenAPITools/Org.OpenAPITools.csproj

View File

@@ -0,0 +1,27 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
VisualStudioVersion = 12.0.0.0
MinimumVisualStudioVersion = 10.0.0.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.Build.0 = Release|Any CPU
{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU
{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU
{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,131 @@
# Org.OpenAPITools - the C# library for the Dummy
To test name, parameter mapping options
This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: 1.0.0
- SDK version: 1.0.0
- Build package: org.openapitools.codegen.languages.CSharpClientCodegen
<a id="frameworks-supported"></a>
## Frameworks supported
<a id="dependencies"></a>
## Dependencies
- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.13.0 or later
- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.2 or later
- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later
- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later
The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages:
```
Install-Package RestSharp
Install-Package Newtonsoft.Json
Install-Package JsonSubTypes
Install-Package System.ComponentModel.Annotations
```
NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742).
NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406).
<a id="installation"></a>
## Installation
Run the following command to generate the DLL
- [Mac/Linux] `/bin/sh build.sh`
- [Windows] `build.bat`
Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces:
```csharp
using Org.OpenAPITools.Api;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Model;
```
<a id="packaging"></a>
## Packaging
A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages.
This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly:
```
nuget pack -Build -OutputDirectory out Org.OpenAPITools.csproj
```
Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual.
<a id="usage"></a>
## Usage
To use the API client with a HTTP proxy, setup a `System.Net.WebProxy`
```csharp
Configuration c = new Configuration();
System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/");
webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
c.Proxy = webProxy;
```
<a id="getting-started"></a>
## Getting Started
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Api;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Model;
namespace Example
{
public class Example
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://localhost";
var apiInstance = new FakeApi(config);
var UnderscoreType = 789L; // long | _type
var type = "type_example"; // string | type
var TypeWithUnderscore = "TypeWithUnderscore_example"; // string | type_
var httpDebugOption = "httpDebugOption_example"; // string | http debug option (to test parameter naming option)
try
{
// parameter name mapping test
apiInstance.GetParameterNameMapping(UnderscoreType, type, TypeWithUnderscore, httpDebugOption);
}
catch (ApiException e)
{
Debug.Print("Exception when calling FakeApi.GetParameterNameMapping: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
<a id="documentation-for-api-endpoints"></a>
## Documentation for API Endpoints
All URIs are relative to *http://localhost*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*FakeApi* | [**GetParameterNameMapping**](docs/FakeApi.md#getparameternamemapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test
<a id="documentation-for-models"></a>
## Documentation for Models
- [Model.PropertyNameMapping](docs/PropertyNameMapping.md)
<a id="documentation-for-authorization"></a>
## Documentation for Authorization
Endpoints do not require authorization.

View File

@@ -0,0 +1,67 @@
openapi: 3.0.0
info:
description: "To test name, parameter mapping options"
license:
name: Apache-2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
title: Dummy
version: 1.0.0
servers:
- url: /
paths:
/fake/parameter-name-mapping:
get:
operationId: getParameterNameMapping
parameters:
- description: _type
explode: false
in: header
name: _type
required: true
schema:
format: int64
type: integer
style: simple
- description: type
explode: true
in: query
name: type
required: true
schema:
type: string
style: form
- description: type_
explode: false
in: header
name: type_
required: true
schema:
type: string
style: simple
- description: http debug option (to test parameter naming option)
explode: true
in: query
name: http_debug_option
required: true
schema:
type: string
style: form
responses:
"200":
description: OK
summary: parameter name mapping test
tags:
- fake
components:
schemas:
PropertyNameMapping:
properties:
http_debug_operation:
type: string
_type:
type: string
type:
type: string
type_:
type: string

View File

@@ -0,0 +1,9 @@
# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator)
#
image: Visual Studio 2019
clone_depth: 1
build_script:
- dotnet build -c Release
- dotnet test -c Release
after_build:
- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build

View File

@@ -0,0 +1,99 @@
# Org.OpenAPITools.Api.FakeApi
All URIs are relative to *http://localhost*
| Method | HTTP request | Description |
|--------|--------------|-------------|
| [**GetParameterNameMapping**](FakeApi.md#getparameternamemapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test |
<a id="getparameternamemapping"></a>
# **GetParameterNameMapping**
> void GetParameterNameMapping (long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption)
parameter name mapping test
### Example
```csharp
using System.Collections.Generic;
using System.Diagnostics;
using Org.OpenAPITools.Api;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Model;
namespace Example
{
public class GetParameterNameMappingExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "http://localhost";
var apiInstance = new FakeApi(config);
var UnderscoreType = 789L; // long | _type
var type = "type_example"; // string | type
var TypeWithUnderscore = "TypeWithUnderscore_example"; // string | type_
var httpDebugOption = "httpDebugOption_example"; // string | http debug option (to test parameter naming option)
try
{
// parameter name mapping test
apiInstance.GetParameterNameMapping(UnderscoreType, type, TypeWithUnderscore, httpDebugOption);
}
catch (ApiException e)
{
Debug.Print("Exception when calling FakeApi.GetParameterNameMapping: " + e.Message);
Debug.Print("Status Code: " + e.ErrorCode);
Debug.Print(e.StackTrace);
}
}
}
}
```
#### Using the GetParameterNameMappingWithHttpInfo variant
This returns an ApiResponse object which contains the response data, status code and headers.
```csharp
try
{
// parameter name mapping test
apiInstance.GetParameterNameMappingWithHttpInfo(UnderscoreType, type, TypeWithUnderscore, httpDebugOption);
}
catch (ApiException e)
{
Debug.Print("Exception when calling FakeApi.GetParameterNameMappingWithHttpInfo: " + e.Message);
Debug.Print("Status Code: " + e.ErrorCode);
Debug.Print(e.StackTrace);
}
```
### Parameters
| Name | Type | Description | Notes |
|------|------|-------------|-------|
| **UnderscoreType** | **long** | _type | |
| **type** | **string** | type | |
| **TypeWithUnderscore** | **string** | type_ | |
| **httpDebugOption** | **string** | http debug option (to test parameter naming option) | |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | OK | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@@ -0,0 +1,13 @@
# Org.OpenAPITools.Model.PropertyNameMapping
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**HttpDebugOperation** | **string** | | [optional]
**UnderscoreType** | **string** | | [optional]
**Type** | **string** | | [optional]
**TypeWithUnderscore** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -0,0 +1,57 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=$(git remote)
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@@ -0,0 +1,69 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using Xunit;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Api;
namespace Org.OpenAPITools.Test.Api
{
/// <summary>
/// Class for testing FakeApi
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the API endpoint.
/// </remarks>
public class FakeApiTests : IDisposable
{
private FakeApi instance;
public FakeApiTests()
{
instance = new FakeApi();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of FakeApi
/// </summary>
[Fact]
public void InstanceTest()
{
// TODO uncomment below to test 'IsType' FakeApi
//Assert.IsType<FakeApi>(instance);
}
/// <summary>
/// Test GetParameterNameMapping
/// </summary>
[Fact]
public void GetParameterNameMappingTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long UnderscoreType = null;
//string type = null;
//string TypeWithUnderscore = null;
//string httpDebugOption = null;
//instance.GetParameterNameMapping(UnderscoreType, type, TypeWithUnderscore, httpDebugOption);
}
}
}

View File

@@ -0,0 +1,93 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing PropertyNameMapping
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class PropertyNameMappingTests : IDisposable
{
// TODO uncomment below to declare an instance variable for PropertyNameMapping
//private PropertyNameMapping instance;
public PropertyNameMappingTests()
{
// TODO uncomment below to create an instance of PropertyNameMapping
//instance = new PropertyNameMapping();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of PropertyNameMapping
/// </summary>
[Fact]
public void PropertyNameMappingInstanceTest()
{
// TODO uncomment below to test "IsType" PropertyNameMapping
//Assert.IsType<PropertyNameMapping>(instance);
}
/// <summary>
/// Test the property 'HttpDebugOperation'
/// </summary>
[Fact]
public void HttpDebugOperationTest()
{
// TODO unit test for the property 'HttpDebugOperation'
}
/// <summary>
/// Test the property 'UnderscoreType'
/// </summary>
[Fact]
public void UnderscoreTypeTest()
{
// TODO unit test for the property 'UnderscoreType'
}
/// <summary>
/// Test the property 'Type'
/// </summary>
[Fact]
public void TypeTest()
{
// TODO unit test for the property 'Type'
}
/// <summary>
/// Test the property 'TypeWithUnderscore'
/// </summary>
[Fact]
public void TypeWithUnderscoreTest()
{
// TODO unit test for the property 'TypeWithUnderscore'
}
}
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Org.OpenAPITools.Test</AssemblyName>
<RootNamespace>Org.OpenAPITools.Test</RootNamespace>
<TargetFramework>net7.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>annotations</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Org.OpenAPITools\Org.OpenAPITools.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,397 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Mime;
using Org.OpenAPITools.Client;
namespace Org.OpenAPITools.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IFakeApiSync : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// parameter name mapping test
/// </summary>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <returns></returns>
void GetParameterNameMapping(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0);
/// <summary>
/// parameter name mapping test
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> GetParameterNameMappingWithHttpInfo(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0);
#endregion Synchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IFakeApiAsync : IApiAccessor
{
#region Asynchronous Operations
/// <summary>
/// parameter name mapping test
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task GetParameterNameMappingAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// parameter name mapping test
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> GetParameterNameMappingWithHttpInfoAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IFakeApi : IFakeApiSync, IFakeApiAsync
{
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class FakeApi : IFakeApi
{
private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="FakeApi"/> class.
/// </summary>
/// <returns></returns>
public FakeApi() : this((string)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FakeApi"/> class.
/// </summary>
/// <returns></returns>
public FakeApi(string basePath)
{
this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations(
Org.OpenAPITools.Client.GlobalConfiguration.Instance,
new Org.OpenAPITools.Client.Configuration { BasePath = basePath }
);
this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath);
this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="FakeApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public FakeApi(Org.OpenAPITools.Client.Configuration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations(
Org.OpenAPITools.Client.GlobalConfiguration.Instance,
configuration
);
this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath);
ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="FakeApi"/> class
/// using a Configuration object and client instance.
/// </summary>
/// <param name="client">The client interface for synchronous API access.</param>
/// <param name="asyncClient">The client interface for asynchronous API access.</param>
/// <param name="configuration">The configuration object.</param>
public FakeApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration)
{
if (client == null) throw new ArgumentNullException("client");
if (asyncClient == null) throw new ArgumentNullException("asyncClient");
if (configuration == null) throw new ArgumentNullException("configuration");
this.Client = client;
this.AsynchronousClient = asyncClient;
this.Configuration = configuration;
this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// The client for accessing this underlying API asynchronously.
/// </summary>
public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; }
/// <summary>
/// The client for accessing this underlying API synchronously.
/// </summary>
public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public string GetBasePath()
{
return this.Configuration.BasePath;
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// parameter name mapping test
/// </summary>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <returns></returns>
public void GetParameterNameMapping(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0)
{
GetParameterNameMappingWithHttpInfo(UnderscoreType, type, TypeWithUnderscore, httpDebugOption);
}
/// <summary>
/// parameter name mapping test
/// </summary>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <returns>ApiResponse of Object(void)</returns>
public Org.OpenAPITools.Client.ApiResponse<Object> GetParameterNameMappingWithHttpInfo(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0)
{
// verify the required parameter 'type' is set
if (type == null)
{
throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'type' when calling FakeApi->GetParameterNameMapping");
}
// verify the required parameter 'TypeWithUnderscore' is set
if (TypeWithUnderscore == null)
{
throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'TypeWithUnderscore' when calling FakeApi->GetParameterNameMapping");
}
// verify the required parameter 'httpDebugOption' is set
if (httpDebugOption == null)
{
throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'httpDebugOption' when calling FakeApi->GetParameterNameMapping");
}
Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions();
string[] _contentTypes = new string[] {
};
// to determine the Accept header
string[] _accepts = new string[] {
};
var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null)
{
localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
}
var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null)
{
localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
}
localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "type", type));
localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "http_debug_option", httpDebugOption));
localVarRequestOptions.HeaderParameters.Add("_type", Org.OpenAPITools.Client.ClientUtils.ParameterToString(UnderscoreType)); // header parameter
localVarRequestOptions.HeaderParameters.Add("type_", Org.OpenAPITools.Client.ClientUtils.ParameterToString(TypeWithUnderscore)); // header parameter
localVarRequestOptions.Operation = "FakeApi.GetParameterNameMapping";
localVarRequestOptions.OperationIndex = operationIndex;
// make the HTTP request
var localVarResponse = this.Client.Get<Object>("/fake/parameter-name-mapping", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetParameterNameMapping", localVarResponse);
if (_exception != null)
{
throw _exception;
}
}
return localVarResponse;
}
/// <summary>
/// parameter name mapping test
/// </summary>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task GetParameterNameMappingAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await GetParameterNameMappingWithHttpInfoAsync(UnderscoreType, type, TypeWithUnderscore, httpDebugOption, operationIndex, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// parameter name mapping test
/// </summary>
/// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="UnderscoreType">_type</param>
/// <param name="type">type</param>
/// <param name="TypeWithUnderscore">type_</param>
/// <param name="httpDebugOption">http debug option (to test parameter naming option)</param>
/// <param name="operationIndex">Index associated with the operation.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<Org.OpenAPITools.Client.ApiResponse<Object>> GetParameterNameMappingWithHttpInfoAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// verify the required parameter 'type' is set
if (type == null)
{
throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'type' when calling FakeApi->GetParameterNameMapping");
}
// verify the required parameter 'TypeWithUnderscore' is set
if (TypeWithUnderscore == null)
{
throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'TypeWithUnderscore' when calling FakeApi->GetParameterNameMapping");
}
// verify the required parameter 'httpDebugOption' is set
if (httpDebugOption == null)
{
throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'httpDebugOption' when calling FakeApi->GetParameterNameMapping");
}
Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions();
string[] _contentTypes = new string[] {
};
// to determine the Accept header
string[] _accepts = new string[] {
};
var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null)
{
localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
}
var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null)
{
localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
}
localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "type", type));
localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "http_debug_option", httpDebugOption));
localVarRequestOptions.HeaderParameters.Add("_type", Org.OpenAPITools.Client.ClientUtils.ParameterToString(UnderscoreType)); // header parameter
localVarRequestOptions.HeaderParameters.Add("type_", Org.OpenAPITools.Client.ClientUtils.ParameterToString(TypeWithUnderscore)); // header parameter
localVarRequestOptions.Operation = "FakeApi.GetParameterNameMapping";
localVarRequestOptions.OperationIndex = operationIndex;
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<Object>("/fake/parameter-name-mapping", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetParameterNameMapping", localVarResponse);
if (_exception != null)
{
throw _exception;
}
}
return localVarResponse;
}
}
}

View File

@@ -0,0 +1,830 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;
using RestSharp.Serializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer
{
private readonly IReadableConfiguration _configuration;
private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
public CustomJsonCodec(IReadableConfiguration configuration)
{
_configuration = configuration;
}
public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration)
{
_serializerSettings = serializerSettings;
_configuration = configuration;
}
/// <summary>
/// Serialize the object into a JSON string.
/// </summary>
/// <param name="obj">Object to be serialized.</param>
/// <returns>A JSON string.</returns>
public string Serialize(object obj)
{
if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema)
{
// the object to be serialized is an oneOf/anyOf schema
return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson();
}
else
{
return JsonConvert.SerializeObject(obj, _serializerSettings);
}
}
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public T Deserialize<T>(RestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(RestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
// TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
var bytes = response.RawBytes;
if (response.Headers != null)
{
var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath)
? Path.GetTempPath()
: _configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in response.Headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, bytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(bytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return Convert.ChangeType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept;
public SupportsContentType SupportsContentType => contentType =>
contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) ||
contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase);
public ContentType ContentType { get; set; } = RestSharp.ContentType.Json;
public DataFormat DataFormat => DataFormat.Json;
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
/// encapsulating general REST accessor use cases.
/// </summary>
public partial class ApiClient : ISynchronousClient, IAsynchronousClient
{
private readonly string _baseUrl;
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer" /> object.
/// These settings can be adjusted to accommodate custom serialization rules.
/// </summary>
public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(RestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(RestRequest request, RestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
/// </summary>
public ApiClient()
{
_baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />
/// </summary>
/// <param name="basePath">The target service's base path in URL format.</param>
/// <exception cref="ArgumentException"></exception>
public ApiClient(string basePath)
{
if (string.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
_baseUrl = basePath;
}
/// <summary>
/// Constructs the RestSharp version of an http method
/// </summary>
/// <param name="method">Swagger Client Custom HttpMethod</param>
/// <returns>RestSharp's HttpMethod instance.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private RestSharpMethod Method(HttpMethod method)
{
RestSharpMethod other;
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.Get;
break;
case HttpMethod.Post:
other = RestSharpMethod.Post;
break;
case HttpMethod.Put:
other = RestSharpMethod.Put;
break;
case HttpMethod.Delete:
other = RestSharpMethod.Delete;
break;
case HttpMethod.Head:
other = RestSharpMethod.Head;
break;
case HttpMethod.Options:
other = RestSharpMethod.Options;
break;
case HttpMethod.Patch:
other = RestSharpMethod.Patch;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
}
return other;
}
/// <summary>
/// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>.
/// At this point, all information for querying the service is known. Here, it is simply
/// mapped into the RestSharp request.
/// </summary>
/// <param name="method">The http verb.</param>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>[private] A new RestRequest instance.</returns>
/// <exception cref="ArgumentNullException"></exception>
private RestRequest NewRequest(
HttpMethod method,
string path,
RequestOptions options,
IReadableConfiguration configuration)
{
if (path == null) throw new ArgumentNullException("path");
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(path, Method(method));
if (options.PathParameters != null)
{
foreach (var pathParam in options.PathParameters)
{
request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment);
}
}
if (options.QueryParameters != null)
{
foreach (var queryParam in options.QueryParameters)
{
foreach (var value in queryParam.Value)
{
request.AddQueryParameter(queryParam.Key, value);
}
}
}
if (configuration.DefaultHeaders != null)
{
foreach (var headerParam in configuration.DefaultHeaders)
{
request.AddHeader(headerParam.Key, headerParam.Value);
}
}
if (options.HeaderParameters != null)
{
foreach (var headerParam in options.HeaderParameters)
{
foreach (var value in headerParam.Value)
{
request.AddHeader(headerParam.Key, value);
}
}
}
if (options.FormParameters != null)
{
foreach (var formParam in options.FormParameters)
{
request.AddParameter(formParam.Key, formParam.Value);
}
}
if (options.Data != null)
{
if (options.Data is Stream stream)
{
var contentType = "application/octet-stream";
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
contentType = contentTypes[0];
}
var bytes = ClientUtils.ReadAsBytes(stream);
request.AddParameter(contentType, bytes, ParameterType.RequestBody);
}
else
{
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json")))
{
request.RequestFormat = DataFormat.Json;
}
else
{
// TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default.
}
}
else
{
// Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly.
request.RequestFormat = DataFormat.Json;
}
request.AddJsonBody(options.Data);
}
}
if (options.FileParameters != null)
{
foreach (var fileParam in options.FileParameters)
{
foreach (var file in fileParam.Value)
{
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
else
request.AddFile(fileParam.Key, bytes, "no_file_name_provided");
}
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(RestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent)
{
ErrorText = response.ErrorMessage,
Cookies = new List<Cookie>()
};
if (response.Headers != null)
{
foreach (var responseHeader in response.Headers)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.ContentHeaders != null)
{
foreach (var responseHeader in response.ContentHeaders)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies.Cast<Cookie>())
{
transformed.Cookies.Add(
new Cookie(
responseCookies.Name,
responseCookies.Value,
responseCookies.Path,
responseCookies.Domain)
);
}
}
return transformed;
}
private ApiResponse<T> Exec<T>(RestRequest request, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
var cookies = new CookieContainer();
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
cookies.Add(new Cookie(cookie.Name, cookie.Value));
}
}
var clientOptions = new RestClientOptions(baseUrl)
{
ClientCertificates = configuration.ClientCertificates,
CookieContainer = cookies,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent,
UseDefaultCredentials = configuration.UseDefaultCredentials,
RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback
};
RestClient client = new RestClient(clientOptions,
configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)));
InterceptRequest(request);
RestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
var policyResult = policy.ExecuteAndCapture(() => client.Execute(request));
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>(request)
{
ErrorException = policyResult.FinalException
};
}
else
{
response = client.Execute<T>(request);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
try
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
catch (Exception ex)
{
throw ex.InnerException != null ? ex.InnerException : ex;
}
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
else if (typeof(T).Name == "Byte[]") // for byte response
{
response.Data = (T)(object)response.RawBytes;
}
else if (typeof(T).Name == "String") // for string response
{
response.Data = (T)(object)response.Content;
}
InterceptResponse(request, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
var clientOptions = new RestClientOptions(baseUrl)
{
ClientCertificates = configuration.ClientCertificates,
MaxTimeout = configuration.Timeout,
Proxy = configuration.Proxy,
UserAgent = configuration.UserAgent,
UseDefaultCredentials = configuration.UseDefaultCredentials
};
RestClient client = new RestClient(clientOptions,
configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)));
InterceptRequest(request);
RestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>(request)
{
ErrorException = policyResult.FinalException
};
}
else
{
response = await client.ExecuteAsync<T>(request, cancellationToken).ConfigureAwait(false);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
else if (typeof(T).Name == "Byte[]") // for byte response
{
response.Data = (T)(object)response.RawBytes;
}
InterceptResponse(request, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies.Cast<Cookie>())
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
#region IAsynchronousClient
/// <summary>
/// Make a HTTP GET request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP POST request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP PUT request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP DELETE request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP HEAD request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP OPTION request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP PATCH request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken);
}
#endregion IAsynchronousClient
#region ISynchronousClient
/// <summary>
/// Make a HTTP GET request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP POST request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP PUT request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP DELETE request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP HEAD request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP OPTION request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP PATCH request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), options, config);
}
#endregion ISynchronousClient
}
}

View File

@@ -0,0 +1,68 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// API Exception
/// </summary>
public class ApiException : Exception
{
/// <summary>
/// Gets or sets the error code (HTTP status code)
/// </summary>
/// <value>The error code (HTTP status code).</value>
public int ErrorCode { get; set; }
/// <summary>
/// Gets or sets the error content (body json object)
/// </summary>
/// <value>The error content (Http response body).</value>
public object ErrorContent { get; private set; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
public Multimap<string, string> Headers { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
public ApiException() { }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="errorCode">HTTP status code.</param>
/// <param name="message">Error message.</param>
public ApiException(int errorCode, string message) : base(message)
{
this.ErrorCode = errorCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="errorCode">HTTP status code.</param>
/// <param name="message">Error message.</param>
/// <param name="errorContent">Error content.</param>
/// <param name="headers">HTTP Headers.</param>
public ApiException(int errorCode, string message, object errorContent = null, Multimap<string, string> headers = null) : base(message)
{
this.ErrorCode = errorCode;
this.ErrorContent = errorContent;
this.Headers = headers;
}
}
}

View File

@@ -0,0 +1,166 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Net;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Provides a non-generic contract for the ApiResponse wrapper.
/// </summary>
public interface IApiResponse
{
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
Type ResponseType { get; }
/// <summary>
/// The content of this response
/// </summary>
Object Content { get; }
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
string ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
List<Cookie> Cookies { get; set; }
/// <summary>
/// The raw content of this response
/// </summary>
string RawContent { get; }
}
/// <summary>
/// API Response
/// </summary>
public class ApiResponse<T> : IApiResponse
{
#region Properties
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
public Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets the data (parsed HTTP body)
/// </summary>
/// <value>The data.</value>
public T Data { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
public string ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
public List<Cookie> Cookies { get; set; }
/// <summary>
/// The content of this response
/// </summary>
public Type ResponseType
{
get { return typeof(T); }
}
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
public object Content
{
get { return Data; }
}
/// <summary>
/// The raw content
/// </summary>
public string RawContent { get; }
#endregion Properties
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data, string rawContent)
{
StatusCode = statusCode;
Headers = headers;
Data = data;
RawContent = rawContent;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data) : this(statusCode, headers, data, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null)
{
}
#endregion Constructors
}
}

View File

@@ -0,0 +1,247 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Utility functions providing some benefit to API client consumers.
/// </summary>
public static class ClientUtils
{
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
return match.Success ? match.Groups[1].Value : filename;
}
/// <summary>
/// Convert params to key/value pairs.
/// Use collectionFormat to properly format lists and collections.
/// </summary>
/// <param name="collectionFormat">The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi</param>
/// <param name="name">Key name.</param>
/// <param name="value">Value object.</param>
/// <returns>A multimap of keys with 1..n associated values.</returns>
public static Multimap<string, string> ParameterToMultiMap(string collectionFormat, string name, object value)
{
var parameters = new Multimap<string, string>();
if (value is ICollection collection && collectionFormat == "multi")
{
foreach (var item in collection)
{
parameters.Add(name, ParameterToString(item));
}
}
else if (value is IDictionary dictionary)
{
if(collectionFormat == "deepObject") {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value));
}
}
else {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value));
}
}
}
else
{
parameters.Add(name, ParameterToString(value));
}
return parameters;
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <param name="configuration">An optional configuration instance, providing formatting options used in processing.</param>
/// <returns>Formatted string.</returns>
public static string ParameterToString(object obj, IReadableConfiguration configuration = null)
{
if (obj is DateTime dateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is DateTimeOffset dateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is bool boolean)
return boolean ? "true" : "false";
if (obj is ICollection collection) {
List<string> entries = new List<string>();
foreach (var entry in collection)
entries.Add(ParameterToString(entry, configuration));
return string.Join(",", entries);
}
if (obj is Enum && HasEnumMemberAttrValue(obj))
return GetEnumMemberAttrValue(obj);
return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Serializes the given object when not null. Otherwise return null.
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <returns>Serialized string.</returns>
public static string Serialize(object obj)
{
return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null;
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">string to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Convert stream to byte array
/// </summary>
/// <param name="inputStream">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream inputStream)
{
using (var ms = new MemoryStream())
{
inputStream.CopyTo(ms);
return ms.ToArray();
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON type exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public static string SelectHeaderContentType(string[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
foreach (var contentType in contentTypes)
{
if (IsJsonMime(contentType))
return contentType;
}
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// 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)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public static string SelectHeaderAccept(string[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return string.Join(",", accepts);
}
/// <summary>
/// Provides a case-insensitive check that a provided content type is a known JSON-like content type.
/// </summary>
public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
/// <summary>
/// Check if the given MIME is a JSON MIME.
/// JSON MIME examples:
/// application/json
/// application/json; charset=UTF8
/// APPLICATION/JSON
/// application/vnd.company+json
/// </summary>
/// <param name="mime">MIME</param>
/// <returns>Returns True if MIME type is json.</returns>
public static bool IsJsonMime(string mime)
{
if (string.IsNullOrWhiteSpace(mime)) return false;
return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json");
}
/// <summary>
/// Is the Enum decorated with EnumMember Attribute
/// </summary>
/// <param name="enumVal"></param>
/// <returns>true if found</returns>
private static bool HasEnumMemberAttrValue(object enumVal)
{
if (enumVal == null)
throw new ArgumentNullException(nameof(enumVal));
var enumType = enumVal.GetType();
var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException());
var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
if (attr != null) return true;
return false;
}
/// <summary>
/// Get the EnumMember value
/// </summary>
/// <param name="enumVal"></param>
/// <returns>EnumMember value as string otherwise null</returns>
private static string GetEnumMemberAttrValue(object enumVal)
{
if (enumVal == null)
throw new ArgumentNullException(nameof(enumVal));
var enumType = enumVal.GetType();
var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException());
var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
if (attr != null)
{
return attr.Value;
}
return null;
}
}
}

View File

@@ -0,0 +1,612 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Http;
using System.Net.Security;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration : IReadableConfiguration
{
#region Constants
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "1.0.0";
/// <summary>
/// Identifier for ISO 8601 DateTime Format
/// </summary>
/// <remarks>See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information.</remarks>
// ReSharper disable once InconsistentNaming
public const string ISO8601_DATETIME_FORMAT = "o";
#endregion Constants
#region Static Members
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
var status = (int)response.StatusCode;
if (status >= 400)
{
return new ApiException(status,
string.Format("Error calling {0}: {1}", methodName, response.RawContent),
response.RawContent, response.Headers);
}
if (status == 0)
{
return new ApiException(status,
string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText);
}
return null;
};
#endregion Static Members
#region Private Members
/// <summary>
/// Defines the base path of the target API server.
/// Example: http://localhost:3000/v1/
/// </summary>
private string _basePath;
private bool _useDefaultCredentials = false;
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// This is the key and value comprising the "secret" for accessing an API.
/// </summary>
/// <value>The API key.</value>
private IDictionary<string, string> _apiKey;
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
private IDictionary<string, string> _apiKeyPrefix;
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the servers defined in the OpenAPI spec.
/// </summary>
/// <value>The servers</value>
private IList<IReadOnlyDictionary<string, object>> _servers;
/// <summary>
/// Gets or sets the operation servers defined in the OpenAPI spec.
/// </summary>
/// <value>The operation servers</value>
private IReadOnlyDictionary<string, List<IReadOnlyDictionary<string, object>>> _operationServers;
#endregion Private Members
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration()
{
Proxy = null;
UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp");
BasePath = "http://localhost";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
ApiKeyPrefix = new ConcurrentDictionary<string, string>();
Servers = new List<IReadOnlyDictionary<string, object>>()
{
{
new Dictionary<string, object> {
{"url", ""},
{"description", "No description provided"},
}
}
};
OperationServers = new Dictionary<string, List<IReadOnlyDictionary<string, object>>>()
{
};
// Setting Timeout has side effects (forces ApiClient creation).
Timeout = 100000;
}
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration(
IDictionary<string, string> defaultHeaders,
IDictionary<string, string> apiKey,
IDictionary<string, string> apiKeyPrefix,
string basePath = "http://localhost") : this()
{
if (string.IsNullOrWhiteSpace(basePath))
throw new ArgumentException("The provided basePath is invalid.", "basePath");
if (defaultHeaders == null)
throw new ArgumentNullException("defaultHeaders");
if (apiKey == null)
throw new ArgumentNullException("apiKey");
if (apiKeyPrefix == null)
throw new ArgumentNullException("apiKeyPrefix");
BasePath = basePath;
foreach (var keyValuePair in defaultHeaders)
{
DefaultHeaders.Add(keyValuePair);
}
foreach (var keyValuePair in apiKey)
{
ApiKey.Add(keyValuePair);
}
foreach (var keyValuePair in apiKeyPrefix)
{
ApiKeyPrefix.Add(keyValuePair);
}
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the base path for API access.
/// </summary>
public virtual string BasePath
{
get { return _basePath; }
set { _basePath = value; }
}
/// <summary>
/// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false.
/// </summary>
public virtual bool UseDefaultCredentials
{
get { return _useDefaultCredentials; }
set { _useDefaultCredentials = value; }
}
/// <summary>
/// Gets or sets the default header.
/// </summary>
[Obsolete("Use DefaultHeaders instead.")]
public virtual IDictionary<string, string> DefaultHeader
{
get
{
return DefaultHeaders;
}
set
{
DefaultHeaders = value;
}
}
/// <summary>
/// Gets or sets the default headers.
/// </summary>
public virtual IDictionary<string, string> DefaultHeaders { get; set; }
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
public virtual int Timeout { get; set; }
/// <summary>
/// Gets or sets the proxy
/// </summary>
/// <value>Proxy.</value>
public virtual WebProxy Proxy { get; set; }
/// <summary>
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public virtual string UserAgent { get; set; }
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public virtual string Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public virtual string Password { get; set; }
/// <summary>
/// Gets the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix(string apiKeyIdentifier)
{
string apiKeyValue;
ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue);
string apiKeyPrefix;
if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix))
{
return apiKeyPrefix + " " + apiKeyValue;
}
return apiKeyValue;
}
/// <summary>
/// Gets or sets certificate collection to be sent with requests.
/// </summary>
/// <value>X509 Certificate collection.</value>
public X509CertificateCollection ClientCertificates { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
///
/// This helper property simplifies code generation.
/// </summary>
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public virtual string TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (string.IsNullOrEmpty(value))
{
_tempFolderPath = Path.GetTempPath();
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
{
Directory.CreateDirectory(value);
}
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
{
_tempFolderPath = value;
}
else
{
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
}
/// <summary>
/// Gets or sets the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public virtual string DateTimeFormat
{
get { return _dateTimeFormat; }
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
///
/// Whatever you set here will be prepended to the value defined in AddApiKey.
///
/// An example invocation here might be:
/// <example>
/// ApiKeyPrefix["Authorization"] = "Bearer";
/// </example>
/// … where ApiKey["Authorization"] would then be used to set the value of your bearer token.
///
/// <remarks>
/// OAuth2 workflows should set tokens via AccessToken.
/// </remarks>
/// </summary>
/// <value>The prefix of the API key.</value>
public virtual IDictionary<string, string> ApiKeyPrefix
{
get { return _apiKeyPrefix; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKeyPrefix collection may not be null.");
}
_apiKeyPrefix = value;
}
}
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public virtual IDictionary<string, string> ApiKey
{
get { return _apiKey; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKey collection may not be null.");
}
_apiKey = value;
}
}
/// <summary>
/// Gets or sets the servers.
/// </summary>
/// <value>The servers.</value>
public virtual IList<IReadOnlyDictionary<string, object>> Servers
{
get { return _servers; }
set
{
if (value == null)
{
throw new InvalidOperationException("Servers may not be null.");
}
_servers = value;
}
}
/// <summary>
/// Gets or sets the operation servers.
/// </summary>
/// <value>The operation servers.</value>
public virtual IReadOnlyDictionary<string, List<IReadOnlyDictionary<string, object>>> OperationServers
{
get { return _operationServers; }
set
{
if (value == null)
{
throw new InvalidOperationException("Operation servers may not be null.");
}
_operationServers = value;
}
}
/// <summary>
/// Returns URL based on server settings without providing values
/// for the variables
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index)
{
return GetServerUrl(Servers, index, null);
}
/// <summary>
/// Returns URL based on server settings.
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <param name="inputVariables">Dictionary of the variables and the corresponding values.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index, Dictionary<string, string> inputVariables)
{
return GetServerUrl(Servers, index, inputVariables);
}
/// <summary>
/// Returns URL based on operation server settings.
/// </summary>
/// <param name="operation">Operation associated with the request path.</param>
/// <param name="index">Array index of the server settings.</param>
/// <return>The operation server URL.</return>
public string GetOperationServerUrl(string operation, int index)
{
return GetOperationServerUrl(operation, index, null);
}
/// <summary>
/// Returns URL based on operation server settings.
/// </summary>
/// <param name="operation">Operation associated with the request path.</param>
/// <param name="index">Array index of the server settings.</param>
/// <param name="inputVariables">Dictionary of the variables and the corresponding values.</param>
/// <return>The operation server URL.</return>
public string GetOperationServerUrl(string operation, int index, Dictionary<string, string> inputVariables)
{
if (operation != null && OperationServers.TryGetValue(operation, out var operationServer))
{
return GetServerUrl(operationServer, index, inputVariables);
}
return null;
}
/// <summary>
/// Returns URL based on server settings.
/// </summary>
/// <param name="servers">Dictionary of server settings.</param>
/// <param name="index">Array index of the server settings.</param>
/// <param name="inputVariables">Dictionary of the variables and the corresponding values.</param>
/// <return>The server URL.</return>
private string GetServerUrl(IList<IReadOnlyDictionary<string, object>> servers, int index, Dictionary<string, string> inputVariables)
{
if (index < 0 || index >= servers.Count)
{
throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {servers.Count}.");
}
if (inputVariables == null)
{
inputVariables = new Dictionary<string, string>();
}
IReadOnlyDictionary<string, object> server = servers[index];
string url = (string)server["url"];
if (server.ContainsKey("variables"))
{
// go through each variable and assign a value
foreach (KeyValuePair<string, object> variable in (IReadOnlyDictionary<string, object>)server["variables"])
{
IReadOnlyDictionary<string, object> serverVariables = (IReadOnlyDictionary<string, object>)(variable.Value);
if (inputVariables.ContainsKey(variable.Key))
{
if (((List<string>)serverVariables["enum_values"]).Contains(inputVariables[variable.Key]))
{
url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]);
}
else
{
throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List<string>)serverVariables["enum_values"]}");
}
}
else
{
// use default value
url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]);
}
}
}
return url;
}
/// <summary>
/// Gets and Sets the RemoteCertificateValidationCallback
/// </summary>
public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; }
#endregion Properties
#region Methods
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static string ToDebugReport()
{
string report = "C# SDK (Org.OpenAPITools) Debug Report:\n";
report += " OS: " + System.Environment.OSVersion + "\n";
report += " .NET Framework Version: " + System.Environment.Version + "\n";
report += " Version of the API: 1.0.0\n";
report += " SDK Package Version: 1.0.0\n";
return report;
}
/// <summary>
/// Add Api Key Header.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
/// <returns></returns>
public void AddApiKey(string key, string value)
{
ApiKey[key] = value;
}
/// <summary>
/// Sets the API key prefix.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
public void AddApiKeyPrefix(string key, string value)
{
ApiKeyPrefix[key] = value;
}
#endregion Methods
#region Static Members
/// <summary>
/// Merge configurations.
/// </summary>
/// <param name="first">First configuration.</param>
/// <param name="second">Second configuration.</param>
/// <return>Merged configuration.</return>
public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second)
{
if (second == null) return first ?? GlobalConfiguration.Instance;
Dictionary<string, string> apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value;
foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value;
foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value;
var config = new Configuration
{
ApiKey = apiKey,
ApiKeyPrefix = apiKeyPrefix,
DefaultHeaders = defaultHeaders,
BasePath = second.BasePath ?? first.BasePath,
Timeout = second.Timeout,
Proxy = second.Proxy ?? first.Proxy,
UserAgent = second.UserAgent ?? first.UserAgent,
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat,
ClientCertificates = second.ClientCertificates ?? first.ClientCertificates,
UseDefaultCredentials = second.UseDefaultCredentials,
RemoteCertificateValidationCallback = second.RemoteCertificateValidationCallback ?? first.RemoteCertificateValidationCallback,
};
return config;
}
#endregion Static Members
}
}

View File

@@ -0,0 +1,22 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// A delegate to ExceptionFactory method
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="response">Response</param>
/// <returns>Exceptions</returns>
public delegate Exception ExceptionFactory(string methodName, IApiResponse response);
}

View File

@@ -0,0 +1,67 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System.Collections.Generic;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// <see cref="GlobalConfiguration"/> provides a compile-time extension point for globally configuring
/// API Clients.
/// </summary>
/// <remarks>
/// A customized implementation via partial class may reside in another file and may
/// be excluded from automatic generation via a .openapi-generator-ignore file.
/// </remarks>
public partial class GlobalConfiguration : Configuration
{
#region Private Members
private static readonly object GlobalConfigSync = new { };
private static IReadableConfiguration _globalConfiguration;
#endregion Private Members
#region Constructors
/// <inheritdoc />
private GlobalConfiguration()
{
}
/// <inheritdoc />
public GlobalConfiguration(IDictionary<string, string> defaultHeader, IDictionary<string, string> apiKey, IDictionary<string, string> apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath)
{
}
static GlobalConfiguration()
{
Instance = new GlobalConfiguration();
}
#endregion Constructors
/// <summary>
/// Gets or sets the default Configuration.
/// </summary>
/// <value>Configuration.</value>
public static IReadableConfiguration Instance
{
get { return _globalConfiguration; }
set
{
lock (GlobalConfigSync)
{
_globalConfiguration = value;
}
}
}
}
}

View File

@@ -0,0 +1,33 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Http methods supported by swagger
/// </summary>
public enum HttpMethod
{
/// <summary>HTTP GET request.</summary>
Get,
/// <summary>HTTP POST request.</summary>
Post,
/// <summary>HTTP PUT request.</summary>
Put,
/// <summary>HTTP DELETE request.</summary>
Delete,
/// <summary>HTTP HEAD request.</summary>
Head,
/// <summary>HTTP OPTIONS request.</summary>
Options,
/// <summary>HTTP PATCH request.</summary>
Patch
}
}

View File

@@ -0,0 +1,37 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents configuration aspects required to interact with the API endpoints.
/// </summary>
public interface IApiAccessor
{
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
string GetBasePath();
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
ExceptionFactory ExceptionFactory { get; set; }
}
}

View File

@@ -0,0 +1,100 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Threading.Tasks;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Contract for Asynchronous RESTful API interactions.
///
/// This interface allows consumers to provide a custom API accessor client.
/// </summary>
public interface IAsynchronousClient
{
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the GET http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the POST http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the PUT http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the DELETE http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the HEAD http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the OPTIONS http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Executes a non-blocking call to some <paramref name="path"/> using the PATCH http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>A task eventually representing the response data, decorated with <see cref="ApiResponse{T}"/></returns>
Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}

View File

@@ -0,0 +1,141 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Represents a readable-only configuration contract.
/// </summary>
public interface IReadableConfiguration
{
/// <summary>
/// Gets the access token.
/// </summary>
/// <value>Access token.</value>
string AccessToken { get; }
/// <summary>
/// Gets the API key.
/// </summary>
/// <value>API key.</value>
IDictionary<string, string> ApiKey { get; }
/// <summary>
/// Gets the API key prefix.
/// </summary>
/// <value>API key prefix.</value>
IDictionary<string, string> ApiKeyPrefix { get; }
/// <summary>
/// Gets the base path.
/// </summary>
/// <value>Base path.</value>
string BasePath { get; }
/// <summary>
/// Gets the date time format.
/// </summary>
/// <value>Date time format.</value>
string DateTimeFormat { get; }
/// <summary>
/// Gets the default header.
/// </summary>
/// <value>Default header.</value>
[Obsolete("Use DefaultHeaders instead.")]
IDictionary<string, string> DefaultHeader { get; }
/// <summary>
/// Gets the default headers.
/// </summary>
/// <value>Default headers.</value>
IDictionary<string, string> DefaultHeaders { get; }
/// <summary>
/// Gets the temp folder path.
/// </summary>
/// <value>Temp folder path.</value>
string TempFolderPath { get; }
/// <summary>
/// Gets the HTTP connection timeout (in milliseconds)
/// </summary>
/// <value>HTTP connection timeout.</value>
int Timeout { get; }
/// <summary>
/// Gets the proxy.
/// </summary>
/// <value>Proxy.</value>
WebProxy Proxy { get; }
/// <summary>
/// Gets the user agent.
/// </summary>
/// <value>User agent.</value>
string UserAgent { get; }
/// <summary>
/// Gets the username.
/// </summary>
/// <value>Username.</value>
string Username { get; }
/// <summary>
/// Gets the password.
/// </summary>
/// <value>Password.</value>
string Password { get; }
/// <summary>
/// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false.
/// </summary>
bool UseDefaultCredentials { get; }
/// <summary>
/// Get the servers associated with the operation.
/// </summary>
/// <value>Operation servers.</value>
IReadOnlyDictionary<string, List<IReadOnlyDictionary<string, object>>> OperationServers { get; }
/// <summary>
/// Gets the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
string GetApiKeyWithPrefix(string apiKeyIdentifier);
/// <summary>
/// Gets the Operation server url at the provided index.
/// </summary>
/// <param name="operation">Operation server name.</param>
/// <param name="index">Index of the operation server settings.</param>
/// <returns></returns>
string GetOperationServerUrl(string operation, int index);
/// <summary>
/// Gets certificate collection to be sent with requests.
/// </summary>
/// <value>X509 Certificate collection.</value>
X509CertificateCollection ClientCertificates { get; }
/// <summary>
/// Callback function for handling the validation of remote certificates. Useful for certificate pinning and
/// overriding certificate errors in the scope of a request.
/// </summary>
RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; }
}
}

View File

@@ -0,0 +1,93 @@
/*
* Dummy
*
* To test name, parameter mapping options
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.IO;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Contract for Synchronous RESTful API interactions.
///
/// This interface allows consumers to provide a custom API accessor client.
/// </summary>
public interface ISynchronousClient
{
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the GET http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the POST http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the PUT http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the DELETE http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the HEAD http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the OPTIONS http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
/// <summary>
/// Executes a blocking call to some <paramref name="path"/> using the PATCH http verb.
/// </summary>
/// <param name="path">The relative path to invoke.</param>
/// <param name="options">The request parameters to pass along to the client.</param>
/// <param name="configuration">Per-request configurable settings.</param>
/// <typeparam name="T">The return type.</typeparam>
/// <returns>The response data, decorated with <see cref="ApiResponse{T}"/></returns>
ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null);
}
}

Some files were not shown because too many files have changed in this diff Show More