Compare commits

..

1 Commits

Author SHA1 Message Date
de7037fd7c init 2025-05-02 16:42:30 +00:00
7647 changed files with 9423 additions and 10486 deletions

View File

@ -48,7 +48,6 @@ jobs:
- samples/server/others/kotlin-server/jaxrs-spec-array-response
- samples/server/petstore/kotlin-spring-cloud
- samples/server/petstore/kotlin-misk
- samples/server/petstore/kotlin-misk-config
# comment out due to gradle build failure
#- samples/server/petstore/kotlin-spring-default
# no build.gradle file

View File

@ -15,7 +15,7 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`7.14.0`):
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`7.13.0`):
[![Build Status](https://api.travis-ci.com/OpenAPITools/openapi-generator.svg?branch=master&status=passed)](https://app.travis-ci.com/github/OpenAPITools/openapi-generator/builds)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator)
@ -74,7 +74,6 @@ If you find OpenAPI Generator useful for work, please consider asking your compa
[<img src="https://openapi-generator.tech/img/companies/route4me.png" width="128" height="128">](https://route4me.com/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship)
[<img src="https://openapi-generator.tech/img/companies/dm.png" width="128" height="128">](https://www.dotcom-monitor.com/sponsoring-open-source-projects/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship)
[<img src="https://openapi-generator.tech/img/companies/clickit.jpg" width="128" height="128">](https://www.clickittech.com/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship)
[<img src="https://openapi-generator.tech/img/companies/unified_to.jpg" width="128" height="128">](https://unified.to/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship)
#### Thank you GoDaddy for sponsoring the domain names, Linode for sponsoring the VPS, Checkly for sponsoring the API monitoring and Gradle for sponsoring Develocity
@ -132,8 +131,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
| OpenAPI Generator Version | Release Date | Notes |
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- |
| 7.14.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.14.0-SNAPSHOT/) | 29.05.2025 | Minor release with breaking changes (with fallback) |
| [7.13.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v7.13.0) (latest stable release) | 27.04.2025 | Minor release with breaking changes (with fallback) |
| 7.13.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.13.0-SNAPSHOT/) | 02.04.2025 | Minor release with breaking changes (with fallback) |
| [7.12.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v7.12.0) (latest stable release) | 28.02.2025 | Minor release with breaking changes (with fallback) |
| [6.6.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v6.6.0) | 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) |
@ -196,16 +195,16 @@ See the different versions of the [openapi-generator-cli](https://search.maven.o
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 11 runtime at a minimum):
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.13.0/openapi-generator-cli-7.13.0.jar`
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar`
For **Mac/Linux** users:
```sh
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.13.0/openapi-generator-cli-7.13.0.jar -O openapi-generator-cli.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar -O openapi-generator-cli.jar
```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
```
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.13.0/openapi-generator-cli-7.13.0.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@ -440,7 +439,7 @@ openapi-generator-cli version
To use a specific version of "openapi-generator-cli"
```sh
openapi-generator-cli version-manager set 7.13.0
openapi-generator-cli version-manager set 7.12.0
```
Or install it as dev-dependency:
@ -464,7 +463,7 @@ pip install openapi-generator-cli
To install a specific version
```
pip install openapi-generator-cli==7.13.0
pip install openapi-generator-cli==7.12.0
```
You can also install with [jdk4py](https://github.com/activeviam/jdk4py) instead of java binary. (python>=3.10 is required)
@ -490,7 +489,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
(if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`)
<!-- RELEASE_VERSION -->
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.13.0/openapi-generator-cli-7.13.0.jar)
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar)
<!-- /RELEASE_VERSION -->
To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate`

View File

@ -1,11 +0,0 @@
generatorName: kotlin-misk
outputDir: samples/server/petstore/kotlin-misk-config
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/kotlin-misk
validateSpec: false
additionalProperties:
hideGenerationTimestamp: "true"
moduleClassName: "PetStoreModule"
generateStubImplClasses: true
addModelMoshiJsonAnnotation: true
actionPathPrefix : "samplePrefix"

View File

@ -2,6 +2,7 @@ generatorName: kotlin-misk
outputDir: samples/server/petstore/kotlin-misk
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/kotlin-misk
validateSpec: false
additionalProperties:
hideGenerationTimestamp: "true"
moduleClassName: "PetStoreModule"

View File

@ -18,14 +18,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|actionPathPrefix|Prefix for action path| ||
|addModelMoshiJsonAnnotation|Add a Moshi JSON adapter annotation to all model classes| |true|
|additionalModelTypeAnnotations|Additional annotations for model type(class level annotations). List separated by semicolon(;) or new line (Linux or Windows)| |null|
|apiSuffix|suffix for api classes| |Api|
|artifactId|Generated artifact id (name of jar).| |null|
|artifactVersion|Generated artifact's package version.| |1.0.0|
|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |original|
|generateStubImplClasses|Generate Stub Impl Classes| |false|
|groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools|
|modelMutable|Create mutable models| |false|
|moduleClassName|Name of the generated module class| |OpenApiModule|
@ -276,7 +273,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON||OAS2,OAS3
|JSON||OAS2,OAS3
|XML|✗|OAS2,OAS3
|PROTOBUF|✓|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@ -18,7 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|akkaHttpVersion|The version of akka-http| |10.2.9|
|akkaHttpVersion|The version of akka-http| |10.1.10|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|artifactId|artifactId| |openapi-scala-akka-http-server|

View File

@ -119,18 +119,18 @@ docker run --rm \
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 11 runtime at a minimum):
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar`
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.9.0/openapi-generator-cli-7.9.0.jar`
For **Mac/Linux** users:
```bash
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar -O openapi-generator-cli.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.9.0/openapi-generator-cli-7.9.0.jar -O openapi-generator-cli.jar
```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
```powershell
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.9.0/openapi-generator-cli-7.9.0.jar
```
<!-- /RELEASE_VERSION -->

View File

@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<relativePath>../../pom.xml</relativePath>
</parent>

View File

@ -6,7 +6,7 @@
<artifactId>openapi-generator-project</artifactId>
<groupId>org.openapitools</groupId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<relativePath>../../pom.xml</relativePath>
</parent>

View File

@ -1,5 +1,5 @@
# RELEASE_VERSION
openApiGeneratorVersion=7.14.0-SNAPSHOT
openApiGeneratorVersion=7.13.0
# /RELEASE_VERSION
# BEGIN placeholders

View File

@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<relativePath>../../pom.xml</relativePath>
</parent>

View File

@ -1,3 +1,3 @@
# RELEASE_VERSION
openApiGeneratorVersion=7.14.0-SNAPSHOT
openApiGeneratorVersion=7.13.0
# /RELEASE_VERSION

View File

@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@ -15,7 +15,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@ -19,7 +19,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<dependencies>
<dependency>

View File

@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@ -20,7 +20,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@ -5,7 +5,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<relativePath>../../pom.xml</relativePath>
</parent>

View File

@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<relativePath>../../pom.xml</relativePath>
</parent>

View File

@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<relativePath>../../pom.xml</relativePath>
</parent>

View File

@ -118,6 +118,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
* p2:
* type: string
*
* @return the discriminator.
*/
@Getter public CodegenDiscriminator discriminator;
@Getter @Setter

View File

@ -959,11 +959,11 @@ public class DefaultCodegen implements CodegenConfig {
@Override
@SuppressWarnings("static-method")
public void postProcess() {
System.out.println("############################################################################################");
System.out.println("################################################################################");
System.out.println("# Thanks for using OpenAPI Generator. #");
System.out.println("# We appreciate your support! Please consider donation to help us maintain this project. #");
System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
System.out.println("# https://opencollective.com/openapi_generator/donate #");
System.out.println("############################################################################################");
System.out.println("################################################################################");
}
// override with any special post-processing

View File

@ -1405,6 +1405,7 @@ public class OpenAPINormalizer {
* then simply it to just boolean.
*
* @param schema Schema
* @return Schema
*/
protected void processSimplifyBooleanEnum(Schema schema) {
if (!getRule(SIMPLIFY_BOOLEAN_ENUM)) {
@ -1424,6 +1425,7 @@ public class OpenAPINormalizer {
* then add x-unsigned to use unsigned integer/long instead.
*
* @param schema Schema
* @return Schema
*/
protected void processAddUnsignedToIntegerWithInvalidMaxValue(Schema schema) {
if (!getRule(ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE)) {

View File

@ -157,6 +157,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
* -- SETTER --
* Set whether discriminator value lookup is case-sensitive or not.
*
* @param discriminatorCaseSensitive true if the discriminator value lookup should be case-sensitive.
*/
@Setter protected boolean discriminatorCaseSensitive = true;
@Getter @Setter

View File

@ -137,7 +137,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
@Setter protected String gradleProperties;
@Setter protected String errorObjectType;
@Getter @Setter protected boolean failOnUnknownProperties = false;
@Setter protected boolean supportVertxFuture = false;
protected String authFolder;
/**
* Serialization library.
@ -245,7 +244,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(SUPPORT_URL_QUERY, "Generate toUrlQueryString in POJO (default to true). Available on `native`, `apache-httpclient` libraries."));
cliOptions.add(CliOption.newBoolean(USE_ENUM_CASE_INSENSITIVE, "Use `equalsIgnoreCase` when String for enum comparison", useEnumCaseInsensitive));
cliOptions.add(CliOption.newBoolean(FAIL_ON_UNKNOWN_PROPERTIES, "Fail Jackson de-serialization on unknown properties", this.failOnUnknownProperties));
cliOptions.add(CliOption.newBoolean(SUPPORT_VERTX_FUTURE, "Also generate api methods that return a vertx Future instead of taking a callback. Only `vertx` supports this option. Requires vertx 4 or greater.", this.supportVertxFuture));
cliOptions.add(CliOption.newBoolean(SUPPORT_VERTX_FUTURE, "Also generate api methods that return a vertx Future instead of taking a callback. Only `vertx` supports this option. Requires vertx 4 or greater."));
supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.17.1");
supportedLibraries.put(JERSEY3, "HTTP client: Jersey client 3.1.1. JSON processing: Jackson 2.17.1");
@ -422,7 +421,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
convertPropertyToStringAndWriteBack(ERROR_OBJECT_TYPE, this::setErrorObjectType);
convertPropertyToBooleanAndWriteBack(WEBCLIENT_BLOCKING_OPERATIONS, op -> webclientBlockingOperations = op);
convertPropertyToBooleanAndWriteBack(FAIL_ON_UNKNOWN_PROPERTIES, this::setFailOnUnknownProperties);
convertPropertyToBooleanAndWriteBack(SUPPORT_VERTX_FUTURE, this::setSupportVertxFuture);
// add URL query deepObject support to native, apache-httpclient by default
if (!additionalProperties.containsKey(SUPPORT_URL_QUERY)) {
@ -589,9 +587,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
// The flag below should be set for all Java libraries, but the templates need to be ported
// one by one for each library.
supportsAdditionalPropertiesWithComposedSchema = true;
if (useJakartaEe) {
LOGGER.warn("Jersey 2 is not compatible with Jakarta EE. Please use Jersey 3 or set {} to false.", USE_JAKARTA_EE);
}
} else if (libJersey3) {
additionalProperties.put("jersey3", true);
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
@ -608,7 +603,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
// The flag below should be set for all Java libraries, but the templates need to be ported
// one by one for each library.
supportsAdditionalPropertiesWithComposedSchema = true;
setUseJakartaEe(true);
applyJakartaPackage();
} else if (libNative) {
supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java"));

View File

@ -47,28 +47,17 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class KotlinMiskServerCodegen extends AbstractKotlinCodegen implements BeanValidationFeatures {
private final Logger LOGGER = LoggerFactory.getLogger(KotlinMiskServerCodegen.class);
public static final String MODULE_CLASS_NAME = "moduleClassName";
public static final String ACTION_PATH_PREFIX = "actionPathPrefix";
private final Logger LOGGER = LoggerFactory.getLogger(KotlinMiskServerCodegen.class);
private static final String ROOT_PACKAGE = "rootPackage";
public static final String GENERATE_STUB_IMPL_CLASSES = "generateStubImplClasses";
public static final String ADD_MODEL_MOSHI_JSON_ANNOTATION = "addModelMoshiJsonAnnotation";
private boolean useBeanValidation = true;
@Setter
private boolean generateStubImplClasses = false;
@Setter
private boolean addModelMoshiJsonAnnotation = true;
protected String rootPackage = "org.openapitools.server.api";
protected String apiVersion = "1.0.0-SNAPSHOT";
@Setter protected String moduleClassName = "OpenApiModule";
@Setter protected String actionPathPrefix = "";
@Override
public CodegenType getTag() {
@ -89,12 +78,10 @@ public class KotlinMiskServerCodegen extends AbstractKotlinCodegen implements Be
super();
addSwitch(USE_BEANVALIDATION, "Use BeanValidation API annotations to validate data types", useBeanValidation);
addSwitch(GENERATE_STUB_IMPL_CLASSES, "Generate Stub Impl Classes", generateStubImplClasses);
addSwitch(ADD_MODEL_MOSHI_JSON_ANNOTATION, "Add a Moshi JSON adapter annotation to all model classes", addModelMoshiJsonAnnotation);
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.PROTOBUF))
.wireFormatFeatures(EnumSet.of(WireFormatFeature.PROTOBUF))
.securityFeatures(EnumSet.noneOf(
SecurityFeature.class
))
@ -121,7 +108,6 @@ public class KotlinMiskServerCodegen extends AbstractKotlinCodegen implements Be
outputFolder = "generated-code" + File.separator + "kotlin-misk";
addOption(MODULE_CLASS_NAME, "Name of the generated module class", moduleClassName);
addOption(ACTION_PATH_PREFIX, "Prefix for action path", actionPathPrefix);
apiTestTemplateFiles.clear();
apiTestTemplateFiles.put("api_test.mustache", ".kt");
@ -136,12 +122,8 @@ public class KotlinMiskServerCodegen extends AbstractKotlinCodegen implements Be
apiTemplateFiles.clear();
apiTemplateFiles.put("apiAction.mustache", "Action.kt");
if (generateStubImplClasses) {
apiTemplateFiles.put("apiImpl.mustache", "Impl.kt");
apiTemplateFiles.put("apiInterface.mustache", ".kt");
}
modelTemplateFiles.put("model.mustache", ".kt");
apiPackage = rootPackage + ".api";
@ -166,27 +148,13 @@ public class KotlinMiskServerCodegen extends AbstractKotlinCodegen implements Be
if (additionalProperties.containsKey(MODULE_CLASS_NAME)) {
setModuleClassName((String) additionalProperties.get(MODULE_CLASS_NAME));
}
writePropertyBack(MODULE_CLASS_NAME, moduleClassName);
if (additionalProperties.containsKey(ACTION_PATH_PREFIX)) {
setActionPathPrefix((String) additionalProperties.get(ACTION_PATH_PREFIX));
}
writePropertyBack(ACTION_PATH_PREFIX, actionPathPrefix);
additionalProperties.put(MODULE_CLASS_NAME, moduleClassName);
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
if (additionalProperties.containsKey(GENERATE_STUB_IMPL_CLASSES)) {
setGenerateStubImplClasses(convertPropertyToBoolean(GENERATE_STUB_IMPL_CLASSES));
}
writePropertyBack(GENERATE_STUB_IMPL_CLASSES, generateStubImplClasses);
if (additionalProperties.containsKey(ADD_MODEL_MOSHI_JSON_ANNOTATION)) {
setAddModelMoshiJsonAnnotation(convertPropertyToBoolean(ADD_MODEL_MOSHI_JSON_ANNOTATION));
}
writePropertyBack(ADD_MODEL_MOSHI_JSON_ANNOTATION, addModelMoshiJsonAnnotation);
applyJakartaPackage();
String apiModuleFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator);
@ -243,7 +211,6 @@ public class KotlinMiskServerCodegen extends AbstractKotlinCodegen implements Be
result.put("application/grpc", "MediaTypes.APPLICATION_GRPC");
result.put("application/javascript", "MediaTypes.APPLICATION_JAVASCRIPT");
result.put("application/json", "MediaTypes.APPLICATION_JSON");
result.put("application/jwt", "MediaTypes.APPLICATION_JWT");
result.put("application/octetstream", "MediaTypes.APPLICATION_OCTETSTREAM");
result.put("application/pdf", "MediaTypes.APPLICATION_OCTETSTREAM");
result.put("application/x-protobuf", "MediaTypes.APPLICATION_PROTOBUF");
@ -252,11 +219,10 @@ public class KotlinMiskServerCodegen extends AbstractKotlinCodegen implements Be
result.put("application/zip", "MediaTypes.APPLICATION_ZIP");
result.put("image/gif", "MediaTypes.IMAGE_GIF");
result.put("image/x-icon", "MediaTypes.IMAGE_ICO");
result.put("image/jpeg", "MediaTypes.IMAGE_JPEG");
result.put("image/png", "MediaTypes.IMAGE_PNG");
result.put("image/svg+xml", "MediaTypes.IMAGE_SVG");
result.put("image/tiff", "MediaTypes.IMAGE_TIFF");
result.put("image/x-icon", "MediaTypes.IMAGE_ICO");
result.put("multipart/form-data", "MediaTypes.FORM_DATA");

View File

@ -51,7 +51,7 @@ public class ScalaAkkaHttpServerCodegen extends AbstractScalaCodegen implements
public static final String AKKA_HTTP_VERSION_DESC = "The version of akka-http";
public static final String PEKKO_HTTP_VERSION = "pekkoHttpVersion";
public static final String PEKKO_HTTP_VERSION_DESC = "The version of pekko-http";
public static final String DEFAULT_AKKA_HTTP_VERSION = "10.2.9";
public static final String DEFAULT_AKKA_HTTP_VERSION = "10.1.10";
public static final String DEFAULT_PEKKO_HTTP_VERSION = "1.1.0";
public static final String GENERATE_AS_MANAGED_SOURCES = "asManagedSources";

View File

@ -24,8 +24,8 @@ public class TemplateManagerOptions {
/**
* Constructs a new instance of {@link TemplateManagerOptions}
*
* @param minimalUpdate Minimal update
* @param skipOverwrite Skip overwrite
* @param minimalUpdate See {@link #isMinimalUpdate()}
* @param skipOverwrite See {@link #isSkipOverwrite()}
*/
public TemplateManagerOptions(boolean minimalUpdate, boolean skipOverwrite) {
this.minimalUpdate = minimalUpdate;

View File

@ -0,0 +1,137 @@
[package]
name = "{{{packageName}}}"
version = "{{#lambdaVersion}}{{{packageVersion}}}{{/lambdaVersion}}"
{{#infoEmail}}
authors = ["{{{.}}}"]
{{/infoEmail}}
{{^infoEmail}}
authors = ["OpenAPI Generator team and contributors"]
{{/infoEmail}}
{{#appDescription}}
description = "{{{.}}}"
{{/appDescription}}
{{#licenseInfo}}
license = "{{.}}"
{{/licenseInfo}}
{{^licenseInfo}}
# Override this license by providing a License Object in the OpenAPI.
license = "Unlicense"
{{/licenseInfo}}
edition = "2021"
{{#publishRustRegistry}}
publish = ["{{.}}"]
{{/publishRustRegistry}}
{{#repositoryUrl}}
repository = "{{.}}"
{{/repositoryUrl}}
{{#documentationUrl}}
documentation = "{{.}}"
{{/documentationUrl}}
{{#homePageUrl}}
homepage = "{{.}}"
{{/homePageUrl}}
{{#supportWasm}}
[lib]
crate-type = ["cdylib", "rlib"]
{{/supportWasm}}
[dependencies]
serde = { version = "^1.0", features = ["derive"] }
{{#serdeWith}}
serde_with = { version = "^3.8", default-features = false, features = ["base64", "std", "macros"] }
{{/serdeWith}}
serde_json = "^1.0"
serde_repr = "^0.1"
url = "^2.5"
{{#hasUUIDs}}
uuid = { version = "^1.8", features = ["serde", "v4"] }
{{/hasUUIDs}}
{{#hyper}}
{{#hyper0x}}
hyper = { version = "~0.14", features = ["full"] }
hyper-tls = "~0.5"
{{/hyper0x}}
{{^hyper0x}}
hyper = { version = "^1.3.1", features = ["full"] }
hyper-util = { version = "0.1.5", features = ["client", "client-legacy", "http1", "http2"] }
http-body-util = { version = "0.1.2" }
{{/hyper0x}}
http = "~0.2"
base64 = "~0.7.0"
futures = "^0.3"
{{/hyper}}
{{#withAWSV4Signature}}
aws-sigv4 = "0.3.0"
http = "0.2.5"
secrecy = "0.8.0"
{{/withAWSV4Signature}}
{{#reqwest}}
{{^supportAsync}}
reqwest = { version = "^0.12", default-features = false, features = ["json", "blocking", "multipart"] }
{{#supportMiddleware}}
reqwest-middleware = { version = "^0.4", features = ["json", "blocking", "multipart"] }
{{/supportMiddleware}}
{{/supportAsync}}
{{#supportAsync}}
reqwest = { version = "^0.12", default-features = false, features = ["json", "multipart"] }
{{#supportMiddleware}}
reqwest-middleware = { version = "^0.4", features = ["json", "multipart"] }
{{/supportMiddleware}}
{{#supportTokenSource}}
async-trait = "^0.1"
# TODO: propose to Yoshidan to externalize this as non google related crate, so that it can easily be extended for other cloud providers.
google-cloud-token = "^0.1"
{{/supportTokenSource}}
{{/supportAsync}}
{{/reqwest}}
{{#reqwestTrait}}
async-trait = "^0.1"
reqwest = { version = "^0.12", default-features = false, features = ["json", "multipart"] }
{{#supportMiddleware}}
reqwest-middleware = { version = "^0.4", features = ["json", "multipart"] }
{{/supportMiddleware}}
{{#supportTokenSource}}
# TODO: propose to Yoshidan to externalize this as non google related crate, so that it can easily be extended for other cloud providers.
google-cloud-token = "^0.1"
{{/supportTokenSource}}
{{#mockall}}
mockall = { version = "^0.13", optional = true}
{{/mockall}}
{{#useBonBuilder}}
bon = { version = "2.3", optional = true }
{{/useBonBuilder}}
[features]
default = [{{#supportWasm}}"console_error_panic_hook"{{/supportWasm}}{{^supportWasm}}"native-tls"{{/supportWasm}}]
{{^supportWasm}}
native-tls = ["reqwest/native-tls"]
rustls = ["reqwest/rustls-tls"]
{{/supportWasm}}
{{#supportWasm}}
console_error_panic_hook = ["dep:console_error_panic_hook"]
{{/supportWasm}}
{{#mockall}}
mockall = ["dep:mockall"]
{{/mockall}}
{{#useBonBuilder}}
bon = ["dep:bon"]
{{/useBonBuilder}}
{{/reqwestTrait}}
{{#supportWasm}}
console_error_panic_hook = { version = "0.1", optional = true }
js-sys = "0.3"
serde-wasm-bindgen = "^0.6"
wasm-std = { version = "0.0.1", registry = "unbox-x-group" }
wasm-bindgen = { version = "^0.2", features = ["serde-serialize"] }
wasm-bindgen-futures = "^0.4"
{{/supportWasm}}
[dev-dependencies]
{{#supportWasm}}
wasm-bindgen-test = "0.3"
{{/supportWasm}}
[profile.release]
opt-level = "s"

View File

@ -0,0 +1,24 @@
{{#supportWasm}}
#![no_std]
{{/supportWasm}}
#![allow(unused_imports)]
#![allow(clippy::too_many_arguments)]
{{#supportWasm}}
extern crate alloc;
{{/supportWasm}}
extern crate serde_repr;
extern crate serde;
extern crate serde_json;
extern crate url;
{{#hyper}}
extern crate hyper;
extern crate futures;
{{/hyper}}
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
pub mod apis;
pub mod models;

View File

@ -0,0 +1,241 @@
{{>partial_header}}
use crate::models;
use serde::{Deserialize, Serialize};
{{#supportWasm}}
use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList};
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use alloc::{fmt, format, vec};
use wasm_std::{error, io};
{{/supportWasm}}
{{#models}}
{{#model}}
{{^isEnum}}{{#vendorExtensions.x-rust-has-byte-array}}
use serde_with::serde_as;
{{/vendorExtensions.x-rust-has-byte-array}}{{/isEnum}}
{{#isEnum}}
{{#isInteger}}
use serde_repr::{Serialize_repr,Deserialize_repr};
{{/isInteger}}
{{/isEnum}}
{{#description}}
/// {{{classname}}} : {{{description}}}
{{/description}}
{{!-- for repr(int) enum schemas --}}
{{#isEnum}}
{{#isInteger}}
/// {{{description}}}
#[repr(i64)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize_repr, Deserialize_repr)]
pub enum {{{classname}}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}} = {{{value}}},
{{/enumVars}}{{/allowableValues}}
}
impl std::fmt::Display for {{{classname}}} {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", match self {
{{#allowableValues}}
{{#enumVars}}
Self::{{{name}}} => "{{{value}}}",
{{/enumVars}}
{{/allowableValues}}
})
}
}
{{/isInteger}}
{{/isEnum}}
{{!-- for enum schemas --}}
{{#isEnum}}
{{^isInteger}}
{{#description}}
/// {{{description}}}
{{/description}}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum {{{classname}}} {
{{#allowableValues}}
{{#enumVars}}
#[serde(rename = "{{{value}}}")]
{{{name}}},
{{/enumVars}}{{/allowableValues}}
}
impl std::fmt::Display for {{{classname}}} {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
{{#allowableValues}}
{{#enumVars}}
Self::{{{name}}} => write!(f, "{{{value}}}"),
{{/enumVars}}
{{/allowableValues}}
}
}
}
{{/isInteger}}
impl Default for {{{classname}}} {
fn default() -> {{{classname}}} {
{{#allowableValues}}
Self::{{ enumVars.0.name }}
{{/allowableValues}}
}
}
{{/isEnum}}
{{!-- for schemas that have a discriminator --}}
{{#discriminator}}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "{{{propertyBaseName}}}")]
pub enum {{{classname}}} {
{{^oneOf}}
{{#mappedModels}}
#[serde(rename="{{mappingName}}")]
{{{modelName}}} {
{{#vars}}
{{#description}}
/// {{{.}}}
{{/description}}
#[serde(rename = "{{{baseName}}}"{{^required}}, skip_serializing_if = "Option::is_none"{{/required}})]
{{{name}}}: {{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{^required}}Option<{{/required}}{{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{{dataType}}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}{{^isModel}}{{{dataType}}}{{/isModel}}{{/isEnum}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^required}}>{{/required}},
{{/vars}}
},
{{/mappedModels}}
{{/oneOf}}
{{^oneOf.isEmpty}}
{{#composedSchemas.oneOf}}
{{#description}}
/// {{{.}}}
{{/description}}
{{#baseName}}
#[serde(rename="{{{.}}}")]
{{/baseName}}
{{{name}}}({{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{/isModel}}{{{dataType}}}{{#isModel}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}),
{{/composedSchemas.oneOf}}
{{/oneOf.isEmpty}}
}
impl Default for {{classname}} {
fn default() -> Self {
{{^oneOf}}{{#mappedModels}}{{#-first}}Self::{{modelName}} {
{{#vars}}
{{{name}}}: Default::default(),
{{/vars}}
}{{/-first}}{{/mappedModels}}
{{/oneOf}}{{^oneOf.isEmpty}}{{#composedSchemas.oneOf}}{{#-first}}Self::{{{name}}}(Default::default()){{/-first}}{{/composedSchemas.oneOf}}{{/oneOf.isEmpty}}
}
}
{{/discriminator}}
{{!-- for non-enum schemas --}}
{{^isEnum}}
{{^discriminator}}
{{#vendorExtensions.x-rust-has-byte-array}}#[serde_as]
{{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct {{{classname}}} {
{{#vars}}
{{#description}}
/// {{{.}}}
{{/description}}
{{#isByteArray}}
{{#vendorExtensions.isMandatory}}#[serde_as(as = "serde_with::base64::Base64")]{{/vendorExtensions.isMandatory}}{{^vendorExtensions.isMandatory}}#[serde_as(as = "{{^serdeAsDoubleOption}}Option{{/serdeAsDoubleOption}}{{#serdeAsDoubleOption}}super::DoubleOption{{/serdeAsDoubleOption}}<serde_with::base64::Base64>")]{{/vendorExtensions.isMandatory}}
{{/isByteArray}}
#[serde(rename = "{{{baseName}}}"{{^required}}{{#isNullable}}, default{{^isByteArray}}, with = "::serde_with::rust::double_option"{{/isByteArray}}{{/isNullable}}{{/required}}{{^required}}, skip_serializing_if = "Option::is_none"{{/required}}{{#required}}{{#isNullable}}, deserialize_with = "Option::deserialize"{{/isNullable}}{{/required}})]
pub {{{name}}}: {{!
### Option Start
}}{{#isNullable}}Option<{{/isNullable}}{{^required}}Option<{{/required}}{{!
### Enums
}}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{!
### Non-Enums Start
}}{{^isEnum}}{{!
### Models
}}{{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{{dataType}}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}{{!
### Primative datatypes
}}{{^isModel}}{{#isByteArray}}Vec<u8>{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isModel}}{{!
### Non-Enums End
}}{{/isEnum}}{{!
### Option End (and trailing comma)
}}{{#isNullable}}>{{/isNullable}}{{^required}}>{{/required}},
{{/vars}}
}
impl {{{classname}}} {
{{#description}}
/// {{{.}}}
{{/description}}
pub fn new({{#requiredVars}}{{{name}}}: {{!
### Option Start
}}{{#isNullable}}Option<{{/isNullable}}{{!
### Enums
}}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{!
### Non-Enums
}}{{^isEnum}}{{#isByteArray}}Vec<u8>{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isEnum}}{{!
### Option End
}}{{#isNullable}}>{{/isNullable}}{{!
### Comma for next arguement
}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} {
{{{classname}}} {
{{#vars}}
{{{name}}}{{^required}}: None{{/required}}{{#required}}{{#isModel}}{{^avoidBoxedModels}}: {{^isNullable}}Box::new({{{name}}}){{/isNullable}}{{#isNullable}}if let Some(x) = {{{name}}} {Some(Box::new(x))} else {None}{{/isNullable}}{{/avoidBoxedModels}}{{/isModel}}{{/required}},
{{/vars}}
}
}
}
{{/oneOf.isEmpty}}
{{^oneOf.isEmpty}}
{{! TODO: add other vars that are not part of the oneOf}}
{{#description}}
/// {{{.}}}
{{/description}}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum {{classname}} {
{{#composedSchemas.oneOf}}
{{#description}}
/// {{{.}}}
{{/description}}
{{{name}}}({{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{/isModel}}{{{dataType}}}{{#isModel}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}),
{{/composedSchemas.oneOf}}
}
impl Default for {{classname}} {
fn default() -> Self {
{{#composedSchemas.oneOf}}{{#-first}}Self::{{{name}}}(Default::default()){{/-first}}{{/composedSchemas.oneOf}}
}
}
{{/oneOf.isEmpty}}
{{/discriminator}}
{{/isEnum}}
{{!-- for properties that are of enum type --}}
{{#vars}}
{{#isEnum}}
{{#description}}
/// {{{description}}}
{{/description}}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum {{{enumName}}} {
{{#allowableValues}}
{{#enumVars}}
#[serde(rename = "{{{value}}}")]
{{{name}}},
{{/enumVars}}
{{/allowableValues}}
}
impl Default for {{{enumName}}} {
fn default() -> {{{enumName}}} {
{{#allowableValues}}
Self::{{ enumVars.0.name }}
{{/allowableValues}}
}
}
{{/isEnum}}
{{/vars}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,474 @@
{{>partial_header}}
use reqwest;
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration, ContentType};
{{#supportWasm}}
use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList};
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use alloc::{fmt, format, vec};
use wasm_std::{error, io};
{{/supportWasm}}
{{#operations}}
{{#operation}}
{{#vendorExtensions.x-group-parameters}}
{{#allParams}}
{{#-first}}
/// struct for passing parameters to the method [`{{operationId}}`]
#[derive(Clone, Debug)]
pub struct {{{operationIdCamelCase}}}Params {
{{/-first}}
{{#description}}
/// {{{.}}}
{{/description}}
pub {{{paramName}}}: {{!
### Option Start
}}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{!
### &str and Vec<&str>
}}{{^isUuid}}{{#isString}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isString}}{{/isUuid}}{{!
### UUIDs
}}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isUuid}}{{!
### Models and primative types
}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{!
### Option End
}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{!
### Comma for next arguement
}}{{^-last}},{{/-last}}
{{#-last}}
}
{{/-last}}
{{/allParams}}
{{/vendorExtensions.x-group-parameters}}
{{/operation}}
{{/operations}}
{{#supportMultipleResponses}}
{{#operations}}
{{#operation}}
/// struct for typed successes of method [`{{operationId}}`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum {{{operationIdCamelCase}}}Success {
{{#responses}}
{{#is2xx}}
Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}),
{{/is2xx}}
{{#is3xx}}
Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}),
{{/is3xx}}
{{/responses}}
UnknownValue(serde_json::Value),
}
{{/operation}}
{{/operations}}
{{/supportMultipleResponses}}
{{#operations}}
{{#operation}}
/// struct for typed errors of method [`{{operationId}}`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum {{{operationIdCamelCase}}}Error {
{{#responses}}
{{#is4xx}}
Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}),
{{/is4xx}}
{{#is5xx}}
Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}),
{{/is5xx}}
{{#isDefault}}
DefaultResponse({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}),
{{/isDefault}}
{{/responses}}
UnknownValue(serde_json::Value),
}
{{/operation}}
{{/operations}}
{{#operations}}
{{#operation}}
{{#description}}
/// {{{.}}}
{{/description}}
{{#notes}}
/// {{{.}}}
{{/notes}}
{{#vendorExtensions.x-group-parameters}}
pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{!
### Params
}}params: {{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{!
### Function return type
}}) -> Result<{{!
### Response File Support
}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{!
### Regular Responses
}}{{^isResponseFile}}{{!
### Multi response support
}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{!
### Regular return type
}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{!
### Error Type
}}, Error<{{{operationIdCamelCase}}}Error>> {
{{/vendorExtensions.x-group-parameters}}
{{^vendorExtensions.x-group-parameters}}
pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{!
### Option Start
}}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{!
### &str and Vec<&str>
}}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{!
### UUIDs
}}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{!
### Models and primative types
}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{!
### Option End
}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{!
### Comma for next arguement
}}{{^-last}}, {{/-last}}{{/allParams}}{{!
### Function return type
}}) -> Result<{{!
### Response File Support
}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{!
### Regular Responses
}}{{^isResponseFile}}{{!
### Multi response support
}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{!
### Regular return type
}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{!
### Error Type
}}, Error<{{{operationIdCamelCase}}}Error>> {
{{#allParams.0}}
// add a prefix to parameters to efficiently prevent name collisions
{{/allParams.0}}
{{#allParams}}
let {{{vendorExtensions.x-rust-param-identifier}}} = {{{paramName}}};
{{/allParams}}
{{/vendorExtensions.x-group-parameters}}
let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{vendorExtensions.x-rust-param-identifier}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}.to_string(){{/isContainer}}{{/isPrimitiveType}}{{/isUuid}}{{/isString}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = configuration.client.request(reqwest::Method::{{{httpMethod}}}, &uri_str);
{{#queryParams}}
{{#required}}
{{#isArray}}
req_builder = match "{{collectionFormat}}" {
"multi" => req_builder.query(&{{{vendorExtensions.x-rust-param-identifier}}}.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
_ => req_builder.query(&[("{{{baseName}}}", &{{{vendorExtensions.x-rust-param-identifier}}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
};
{{/isArray}}
{{^isArray}}
{{^isNullable}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{vendorExtensions.x-rust-param-identifier}}}.to_string())]);
{{/isNullable}}
{{#isNullable}}
{{#isDeepObject}}
if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
let params = crate::apis::parse_deep_object("{{{baseName}}}", param_value);
req_builder = req_builder.query(&params);
};
{{/isDeepObject}}
{{^isDeepObject}}
if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &param_value.to_string())]);
};
{{/isDeepObject}}
{{/isNullable}}
{{/isArray}}
{{/required}}
{{^required}}
if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
{{#isArray}}
req_builder = match "{{collectionFormat}}" {
"multi" => req_builder.query(&param_value.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
_ => req_builder.query(&[("{{{baseName}}}", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
};
{{/isArray}}
{{^isArray}}
{{#isDeepObject}}
let params = crate::apis::parse_deep_object("{{{baseName}}}", param_value);
req_builder = req_builder.query(&params);
{{/isDeepObject}}
{{^isDeepObject}}
req_builder = req_builder.query(&[("{{{baseName}}}", &param_value.to_string())]);
{{/isDeepObject}}
{{/isArray}}
}
{{/required}}
{{/queryParams}}
{{#hasAuthMethods}}
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInQuery}}
if let Some(ref apikey) = configuration.api_key {
let key = apikey.key.clone();
let value = match apikey.prefix {
Some(ref prefix) => format!("{} {}", prefix, key),
None => key,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", value)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#hasAuthMethods}}
{{#withAWSV4Signature}}
if let Some(ref aws_v4_key) = configuration.aws_v4_key {
let new_headers = match aws_v4_key.sign(
&uri_str,
"{{{httpMethod}}}",
{{#hasBodyParam}}
{{#bodyParams}}
&serde_json::to_string(&{{{vendorExtensions.x-rust-param-identifier}}}).expect("param should serialize to string"),
{{/bodyParams}}
{{/hasBodyParam}}
{{^hasBodyParam}}
"",
{{/hasBodyParam}}
) {
Ok(new_headers) => new_headers,
Err(err) => return Err(Error::AWSV4SignatureError(err)),
};
for (name, value) in new_headers.iter() {
req_builder = req_builder.header(name.as_str(), value.as_str());
}
}
{{/withAWSV4Signature}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.join(","){{/isArray}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{vendorExtensions.x-rust-param-identifier}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isArray}}.join(","){{/isArray}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isArray}}.join(","){{/isArray}}.to_string());
}
{{/required}}
{{/headerParams}}
{{/hasHeaderParams}}
{{#hasAuthMethods}}
{{#authMethods}}
{{#supportTokenSource}}
// Obtain a token from source provider.
// Tokens can be Id or access tokens depending on the provider type and configuration.
let token = configuration.token_source.token().await.map_err(Error::TokenSource)?;
// The token format is the responsibility of the provider, thus we just set the authorization header with whatever is given.
req_builder = req_builder.header(reqwest::header::AUTHORIZATION, token);
{{/supportTokenSource}}
{{^supportTokenSource}}
{{#isApiKey}}
{{#isKeyInHeader}}
if let Some(ref apikey) = configuration.api_key {
let key = apikey.key.clone();
let value = match apikey.prefix {
Some(ref prefix) => format!("{} {}", prefix, key),
None => key,
};
req_builder = req_builder.header("{{{keyParamName}}}", value);
};
{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}
{{#isBasicBasic}}
if let Some(ref auth_conf) = configuration.basic_auth {
req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
};
{{/isBasicBasic}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/supportTokenSource}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut multipart_form = reqwest{{^supportAsync}}::blocking{{/supportAsync}}::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{^supportAsync}}
{{#required}}
{{^isNullable}}
multipart_form = multipart_form.file("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{vendorExtensions.x-rust-param-identifier}}} {
Some(param_value) => { multipart_form = multipart_form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
multipart_form = multipart_form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/supportAsync}}
{{#supportAsync}}
// TODO: support file upload for '{{{baseName}}}' parameter
{{/supportAsync}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
multipart_form = multipart_form.text("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isArray}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{vendorExtensions.x-rust-param-identifier}}} {
Some(param_value) => { multipart_form = multipart_form.text("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isArray}}.to_string()); },
None => { multipart_form = multipart_form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
multipart_form = multipart_form.text("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isArray}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(multipart_form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut multipart_form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{vendorExtensions.x-rust-param-identifier}}} {
Some(param_value) => { multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
multipart_form_params.insert("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isArray}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{vendorExtensions.x-rust-param-identifier}}} {
Some(param_value) => { multipart_form_params.insert("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isArray}}.to_string()); },
None => { multipart_form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} {
multipart_form_params.insert("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isArray}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&multipart_form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#hasBodyParam}}
{{#bodyParams}}
{{#isFile}}
req_builder = req_builder.body({{{vendorExtensions.x-rust-param-identifier}}});
{{/isFile}}
{{^isFile}}
req_builder = req_builder.json(&{{{vendorExtensions.x-rust-param-identifier}}});
{{/isFile}}
{{/bodyParams}}
{{/hasBodyParam}}
let req = req_builder.build()?;
let resp = configuration.client.execute(req){{#supportAsync}}.await{{/supportAsync}}?;
let status = resp.status();
{{^supportMultipleResponses}}
{{^isResponseFile}}
{{#returnType}}
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
{{/returnType}}
{{/isResponseFile}}
{{/supportMultipleResponses}}
if !status.is_client_error() && !status.is_server_error() {
{{^supportMultipleResponses}}
{{#isResponseFile}}
Ok(resp)
{{/isResponseFile}}
{{^isResponseFile}}
{{^returnType}}
Ok(())
{{/returnType}}
{{#returnType}}
let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
{{#vendorExtensions.x-supports-plain-text}}
ContentType::Text => Ok(content),
{{/vendorExtensions.x-supports-plain-text}}
{{^vendorExtensions.x-supports-plain-text}}
ContentType::Text => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{returnType}}`"))),
{{/vendorExtensions.x-supports-plain-text}}
ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `{{returnType}}`")))),
}
{{/returnType}}
{{/isResponseFile}}
{{/supportMultipleResponses}}
{{#supportMultipleResponses}}
{{#isResponseFile}}
Ok(resp)
{{/isResponseFile}}
{{^isResponseFile}}
let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?;
let entity: Option<{{{operationIdCamelCase}}}Success> = serde_json::from_str(&content).ok();
Ok(ResponseContent { status, content, entity })
{{/isResponseFile}}
{{/supportMultipleResponses}}
} else {
let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?;
let entity: Option<{{{operationIdCamelCase}}}Error> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent { status, content, entity }))
}
}
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,208 @@
{{^supportWasm}}
use std::error;
use std::fmt;
{{/supportWasm}}
{{#supportWasm}}
use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList};
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use alloc::{fmt, format, vec};
use wasm_std::{error, io};
{{/supportWasm}}
{{#withAWSV4Signature}}
use aws_sigv4;
{{/withAWSV4Signature}}
#[derive(Debug, Clone)]
pub struct ResponseContent<T> {
pub status: reqwest::StatusCode,
pub content: String,
pub entity: Option<T>,
}
#[derive(Debug)]
pub enum Error<T> {
Reqwest(reqwest::Error),
{{#supportMiddleware}}
ReqwestMiddleware(reqwest_middleware::Error),
{{/supportMiddleware}}
Serde(serde_json::Error),
Io({{^supportWasm}}std::{{/supportWasm}}io::Error),
ResponseError(ResponseContent<T>),
{{#withAWSV4Signature}}
AWSV4SignatureError(aws_sigv4::http_request::Error),
{{/withAWSV4Signature}}
{{#supportAsync}}
{{#supportTokenSource}}
TokenSource(Box<dyn {{^supportWasm}}std::{{/supportWasm}}error::Error + Send + Sync>),
{{/supportTokenSource}}
{{/supportAsync}}
}
impl <T> fmt::Display for Error<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (module, e) = match self {
Error::Reqwest(e) => ("reqwest", e.to_string()),
{{#supportMiddleware}}
Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()),
{{/supportMiddleware}}
Error::Serde(e) => ("serde", e.to_string()),
Error::Io(e) => ("IO", e.to_string()),
Error::ResponseError(e) => ("response", format!("status code {}", e.status)),
{{#withAWSV4Signature}}
Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()),
{{/withAWSV4Signature}}
{{#supportAsync}}
{{#supportTokenSource}}
Error::TokenSource(e) => ("token source failure", e.to_string()),
{{/supportTokenSource}}
{{/supportAsync}}
};
write!(f, "error in {}: {}", module, e)
}
}
impl <T: fmt::Debug> error::Error for Error<T> {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
{{^supportWasm}}
Error::Reqwest(e) => Some(e),
{{#supportMiddleware}}
Error::ReqwestMiddleware(e) => Some(e),
{{/supportMiddleware}}
Error::Serde(e) => Some(e),
Error::ResponseError(_) => return None,
{{#withAWSV4Signature}}
Error::AWSV4SignatureError(_) => return None,
{{/withAWSV4Signature}}
{{#supportAsync}}
{{#supportTokenSource}}
Error::TokenSource(e) => Some(&**e),
{{/supportTokenSource}}
{{/supportAsync}}
{{/supportWasm}}
{{#supportWasm}}
_ => None,
{{/supportWasm}}
}
}
fn description(&self) -> &str {
match self {
Error::Io(e) => e.description(),
{{^supportWasm}}
Error::Reqwest(e) => e.description(),
{{#supportMiddleware}}
Error::ReqwestMiddleware(e) => e.description(),
{{/supportMiddleware}}
Error::Serde(e) => e.description(),
Error::ResponseError(e) => e.description(),
{{#withAWSV4Signature}}
Error::AWSV4SignatureError(e) => e.description(),
{{/withAWSV4Signature}}
{{#supportAsync}}
{{#supportTokenSource}}
Error::TokenSource(e) => (&**e).description(),
{{/supportTokenSource}}
{{/supportAsync}}
{{/supportWasm}}
{{#supportWasm}}
_ => "unknown error",
{{/supportWasm}}
}
}
}
impl <T> From<reqwest::Error> for Error<T> {
fn from(e: reqwest::Error) -> Self {
Error::Reqwest(e)
}
}
{{#supportMiddleware}}
impl<T> From<reqwest_middleware::Error> for Error<T> {
fn from(e: reqwest_middleware::Error) -> Self {
Error::ReqwestMiddleware(e)
}
}
{{/supportMiddleware}}
impl <T> From<serde_json::Error> for Error<T> {
fn from(e: serde_json::Error) -> Self {
Error::Serde(e)
}
}
impl <T> From<{{^supportWasm}}std::{{/supportWasm}}io::Error> for Error<T> {
fn from(e: {{^supportWasm}}std::{{/supportWasm}}io::Error) -> Self {
Error::Io(e)
}
}
pub fn urlencode<T: AsRef<str>>(s: T) -> String {
::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect()
}
pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> {
if let serde_json::Value::Object(object) = value {
let mut params = vec![];
for (key, value) in object {
match value {
serde_json::Value::Object(_) => params.append(&mut parse_deep_object(
&format!("{}[{}]", prefix, key),
value,
)),
serde_json::Value::Array(array) => {
for (i, value) in array.iter().enumerate() {
params.append(&mut parse_deep_object(
&format!("{}[{}][{}]", prefix, key, i),
value,
));
}
},
serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())),
_ => params.push((format!("{}[{}]", prefix, key), value.to_string())),
}
}
return params;
}
unimplemented!("Only objects are supported with style=deepObject")
}
/// Internal use only
/// A content type supported by this client.
#[allow(dead_code)]
enum ContentType {
Json,
Text,
Unsupported(String)
}
impl From<&str> for ContentType {
fn from(content_type: &str) -> Self {
if content_type.starts_with("application") && content_type.contains("json") {
Self::Json
} else if content_type.starts_with("text/plain") {
Self::Text
} else {
Self::Unsupported(content_type.to_string())
}
}
}
{{#apiInfo}}
{{#apis}}
pub mod {{{classFilename}}};
{{/apis}}
{{/apiInfo}}
pub mod configuration;

View File

@ -0,0 +1,137 @@
{{>partial_header}}
{{#supportWasm}}
use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList};
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use alloc::{fmt, format, vec};
use wasm_std::{error, io};
{{/supportWasm}}
{{#withAWSV4Signature}}
{{^supportWasm}}
use std::time::SystemTime;
{{/supportWasm}}
use aws_sigv4::http_request::{sign, SigningSettings, SigningParams, SignableRequest};
use http;
use secrecy::{SecretString, ExposeSecret};
{{/withAWSV4Signature}}
{{#supportTokenSource}}
{{^supportWasm}}
use std::sync::Arc;
{{/supportWasm}}
use google_cloud_token::TokenSource;
use async_trait::async_trait;
{{/supportTokenSource}}
#[derive(Debug, Clone)]
pub struct Configuration {
pub base_path: String,
pub user_agent: Option<String>,
pub client: {{#supportMiddleware}}reqwest_middleware::ClientWithMiddleware{{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client{{/supportMiddleware}},
{{^supportTokenSource}}
pub basic_auth: Option<BasicAuth>,
pub oauth_access_token: Option<String>,
pub bearer_access_token: Option<String>,
pub api_key: Option<ApiKey>,
{{/supportTokenSource}}
{{#withAWSV4Signature}}
pub aws_v4_key: Option<AWSv4Key>,
{{/withAWSV4Signature}}
{{#supportAsync}}
{{#supportTokenSource}}
pub token_source: Arc<dyn TokenSource>,
{{/supportTokenSource}}
{{/supportAsync}}
}
{{^supportTokenSource}}
pub type BasicAuth = (String, Option<String>);
#[derive(Debug, Clone)]
pub struct ApiKey {
pub prefix: Option<String>,
pub key: String,
}
{{/supportTokenSource}}
{{#withAWSV4Signature}}
#[derive(Debug, Clone)]
pub struct AWSv4Key {
pub access_key: String,
pub secret_key: SecretString,
pub region: String,
pub service: String,
}
impl AWSv4Key {
pub fn sign(&self, uri: &str, method: &str, body: &str) -> Result<Vec::<(String, String)>, aws_sigv4::http_request::Error> {
let request = http::Request::builder()
.uri(uri)
.method(method)
.body(body).unwrap();
let signing_settings = SigningSettings::default();
let signing_params = SigningParams::builder()
.access_key(self.access_key.as_str())
.secret_key(self.secret_key.expose_secret().as_str())
.region(self.region.as_str())
.service_name(self.service.as_str())
.time(SystemTime::now())
.settings(signing_settings)
.build()
.unwrap();
let signable_request = SignableRequest::from(&request);
let (mut signing_instructions, _signature) = sign(signable_request, &signing_params)?.into_parts();
let mut additional_headers = Vec::<(String, String)>::new();
if let Some(new_headers) = signing_instructions.take_headers() {
for (name, value) in new_headers.into_iter() {
additional_headers.push((name.expect("header should have name").to_string(),
value.to_str().expect("header value should be a string").to_string()));
}
}
Ok(additional_headers)
}
}
{{/withAWSV4Signature}}
impl Configuration {
pub fn new() -> Configuration {
Configuration::default()
}
}
impl Default for Configuration {
fn default() -> Self {
Configuration {
base_path: "{{{basePath}}}".to_owned(),
user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}},
client: {{#supportMiddleware}}reqwest_middleware::ClientBuilder::new(reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new()).build(){{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new(){{/supportMiddleware}},
{{^supportTokenSource}}
basic_auth: None,
oauth_access_token: None,
bearer_access_token: None,
api_key: None,
{{/supportTokenSource}}
{{#withAWSV4Signature}}
aws_v4_key: None,
{{/withAWSV4Signature}}
{{#supportTokenSource}}
token_source: Arc::new(NoopTokenSource{}),
{{/supportTokenSource}}
}
}
}
{{#supportTokenSource}}
#[derive(Debug)]
struct NoopTokenSource{}
#[async_trait]
impl TokenSource for NoopTokenSource {
async fn token(&self) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
panic!("This is dummy token source. You can use TokenSourceProvider from 'google_cloud_auth' crate, or any other compatible crate.")
}
}
{{/supportTokenSource}}

View File

@ -12,8 +12,8 @@ import {{javaxPackage}}.ws.rs.core.GenericType;
{{/imports}}
{{#useBeanValidation}}
import {{javaxPackage}}.validation.constraints.*;
import {{javaxPackage}}.validation.Valid;
import jakarta.validation.constraints.*;
import jakarta.validation.Valid;
{{/useBeanValidation}}
import java.util.ArrayList;

View File

@ -17,8 +17,8 @@ import java.util.List;
import java.util.Map;
{{#useBeanValidation}}
import {{javaxPackage}}.validation.constraints.*;
import {{javaxPackage}}.validation.Valid;
import jakarta.validation.constraints.*;
import jakarta.validation.Valid;
{{/useBeanValidation}}
/**

View File

@ -152,6 +152,7 @@ dependencies {
{{#useReflectionEqualsHashCode}}
implementation "org.apache.commons:commons-lang3:$commons_lang3_version"
{{/useReflectionEqualsHashCode}}
testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version"
}

View File

@ -42,8 +42,8 @@ import android.os.Parcelable;
import android.os.Parcel;
{{/parcelableModel}}
{{#useBeanValidation}}
import {{javaxPackage}}.validation.constraints.*;
import {{javaxPackage}}.validation.Valid;
import jakarta.validation.constraints.*;
import jakarta.validation.Valid;
{{/useBeanValidation}}
{{#performBeanValidation}}
import org.hibernate.validator.constraints.*;

View File

@ -408,14 +408,8 @@
<jackson-version>2.17.1</jackson-version>
<jackson-databind-version>2.17.1</jackson-databind-version>
<jackson-databind-nullable-version>0.2.6</jackson-databind-nullable-version>
{{#useJakartaEe}}
<jakarta-annotation-version>2.1.1</jakarta-annotation-version>
<beanvalidation-version>3.0.2</beanvalidation-version>
{{/useJakartaEe}}
{{^useJakartaEe}}
<jakarta-annotation-version>1.3.5</jakarta-annotation-version>
<beanvalidation-version>2.0.2</beanvalidation-version>
{{/useJakartaEe}}
<junit-version>5.10.0</junit-version>
{{#hasHttpSignatureMethods}}
<http-signature-version>1.8</http-signature-version>

View File

@ -1 +1 @@
{{#isFormParam}}{{^isFile}}{{>paramDoc}}{{#useBeanValidation}} @Valid{{/useBeanValidation}} {{#isModel}}@RequestPart{{/isModel}}{{^isModel}}{{#isArray}}@RequestPart{{/isArray}}{{^isArray}}{{#reactive}}@RequestPart{{/reactive}}{{^reactive}}@RequestParam{{/reactive}}{{/isArray}}{{/isModel}}(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}){{>dateTimeParam}} {{^required}}{{#useOptional}}Optional<{{/useOptional}}{{/required}}{{{dataType}}}{{^required}}{{#useOptional}}>{{/useOptional}}{{/required}} {{paramName}}{{/isFile}}{{#isFile}}{{>paramDoc}} @RequestPart(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{#isArray}}List<{{/isArray}}{{#reactive}}Flux<Part>{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{#isArray}}>{{/isArray}} {{paramName}}{{/isFile}}{{/isFormParam}}
{{#isFormParam}}{{^isFile}}{{>paramDoc}}{{#useBeanValidation}} @Valid{{/useBeanValidation}} {{#isModel}}@RequestPart{{/isModel}}{{^isModel}}{{#isArray}}@RequestPart{{/isArray}}{{^isArray}}{{#reactive}}@RequestPart{{/reactive}}{{^reactive}}@RequestParam{{/reactive}}{{/isArray}}{{/isModel}}(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}){{>dateTimeParam}} {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}{{>paramDoc}} @RequestPart(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{#isArray}}List<{{/isArray}}{{#reactive}}Flux<Part>{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{#isArray}}>{{/isArray}} {{paramName}}{{/isFile}}{{/isFormParam}}

View File

@ -92,15 +92,6 @@ class {{declspec}} {{classname}}
{
public:
{{classname}}();
{{classname}}(utility::string_t str);
operator utility::string_t() const {
return enumToStrMap.at(getValue());
}
{{! operator std::string() const {
return enumToStrMap.at(getValue());
} }}
virtual ~{{classname}}();
/////////////////////////////////////////////
@ -133,21 +124,6 @@ public:
protected:
e{{classname}} m_value;
std::map<e{{classname}},utility::string_t> enumToStrMap = {
{{#allowableValues}}
{{#enumVars}}
{ e{{classname}}::{{classname}}_{{{name}}}, "{{{name}}}" }{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
};
std::map<utility::string_t,e{{classname}}> strToEnumMap = {
{{#allowableValues}}
{{#enumVars}}
{ "{{{name}}}", e{{classname}}::{{classname}}_{{{name}}} }{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
};
};
{{/isEnum}}
{{^isEnum}}

View File

@ -176,10 +176,6 @@ void {{classname}}::setValue({{classname}}::e{{classname}} const value)
m_value = value;
}
{{classname}}::{{classname}}(utility::string_t str){
setValue( strToEnumMap[str] );
}
{{/isEnum}}
{{^isEnum}}

View File

@ -32,22 +32,22 @@ import misk.web.mediatype.MediaTypes
{{#imports}}import {{import}}
{{/imports}}
/**
* @TODO("Fill out implementation")
*/
{{#operations}}
/**
* Generated file, please change {{classname}}Impl.
*/
@Singleton
class {{classname}}Action @Inject constructor(
) : WebAction {
private val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}: {{classname}}
) : WebAction, {{classname}} {
{{#operation}}
@{{httpMethod}}("{{actionPathPrefix}}{{path}}")
@{{httpMethod}}("{{path}}")
@Description("{{{summary}}}"){{#hasConsumes}}
@RequestContentType({{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}){{/hasConsumes}}{{#hasProduces}}
@ResponseContentType({{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}){{/hasProduces}}
@LogRequestResponse(bodySampling = 1.0, errorBodySampling = 1.0)
fun {{operationId}}({{#allParams}}
{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}} {
override fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}} {
TODO()
}
{{/operation}}

View File

@ -30,8 +30,7 @@ class {{classname}}Impl @Inject constructor(
): {{classname}} {
{{#operation}}
override fun {{operationId}}({{#allParams}}
{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}} {
override fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}} {
TODO()
}
{{/operation}}

View File

@ -23,8 +23,7 @@ import misk.web.RequestHeader
interface {{classname}} {
{{#operation}}
fun {{operationId}}({{#allParams}}
{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}} {
fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}}
{{/operation}}
}
{{/operations}}

View File

@ -16,7 +16,7 @@ import misk.web.RequestHeader
@MiskTest(startService = true)
internal class {{classname}}Test {
@Inject private lateinit var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}: {{classname}}Action
@Inject private lateinit var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}: {{classname}}
{{#operations}}
{{#operation}}

View File

@ -9,8 +9,8 @@ version = "{{artifactVersion}}"
dependencies {
implementation("jakarta.validation:jakarta.validation-api:3.1.1")
implementation("com.squareup.misk:misk:2025.04.27.230742-6035cb3")
implementation("com.squareup.moshi:moshi:1.15.2")
implementation("com.squareup.misk:misk:2025.04.02.195630-a61d550")
//implementation("com.squareup.wire:wire-runtime:5.2.1")
testImplementation("com.squareup.misk:misk-testing:2025.02.11.123913-8a41324")
testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")

View File

@ -3,6 +3,7 @@ package {{modelPackage}}
{{#imports}}
import {{import}}
{{/imports}}
{{#models}}
{{#model}}
{{#isEnum}}
@ -15,9 +16,6 @@ enum class {{classname}} {
}
{{/isEnum}}
{{^isEnum}}
{{#addModelMoshiJsonAnnotation}}import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true){{/addModelMoshiJsonAnnotation}}
data class {{classname}}(
{{#vars}}
{{#description}}

View File

@ -301,7 +301,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}}{{/parentSchema}}{{^par
{{/required}}
{{#isEnum}}
{{^isContainer}}
$allowedValues = self::{{getter}}AllowableValues();
$allowedValues = $this->{{getter}}AllowableValues();
if (!is_null($this->container['{{name}}']) && !in_array($this->container['{{name}}'], $allowedValues, true)) {
$invalidProperties[] = sprintf(
"invalid value '%s' for '{{name}}', must be one of '%s'",
@ -416,7 +416,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}}{{/parentSchema}}{{^par
}
{{/isNullable}}
{{#isEnum}}
$allowedValues = self::{{getter}}AllowableValues();
$allowedValues = $this->{{getter}}AllowableValues();
{{^isContainer}}
if ({{#isNullable}}!is_null(${{name}}) && {{/isNullable}}!in_array(${{{name}}}, $allowedValues, true)) {
{{#enumUnknownDefaultCase}}

View File

@ -1,16 +1,11 @@
version := "{{artifactVersion}}"
name := "{{artifactId}}"
organization := "{{groupId}}"
scalaVersion := "2.13.16"
scalaVersion := "2.12.20"
libraryDependencies ++= Seq({{#useApachePekko}}
"org.apache.pekko" %% "pekko-stream" % "1.1.3",
"org.apache.pekko" %% "pekko-stream" % "1.0.3",
"org.apache.pekko" %% "pekko-http" % "{{pekkoHttpVersion}}"{{/useApachePekko}}{{^useApachePekko}}
"com.typesafe.akka" %% "akka-stream" % "2.6.21",
"com.typesafe.akka" %% "akka-stream" % "2.5.21",
"com.typesafe.akka" %% "akka-http" % "{{akkaHttpVersion}}"{{/useApachePekko}}
)
scalacOptions ++= Seq(
"-deprecation",
"-feature",
)

View File

@ -6,11 +6,11 @@ import {{akkaImportGroupId}}.http.scaladsl.server.Route
{{/operations}}{{/apis}}{{/apiInfo}}
import {{akkaImportGroupId}}.http.scaladsl.server.Directives._
import {{akkaImportGroupId}}.actor.ActorSystem
import {{akkaImportGroupId}}.stream.Materializer
import {{akkaImportGroupId}}.stream.ActorMaterializer
class Controller({{#apiInfo}}{{#apis}}{{#operations}}{{classVarName}}: {{classname}}{{^-last}}, {{/-last}}{{/operations}}{{/apis}}{{/apiInfo}})(implicit system: ActorSystem, materializer: Materializer) {
class Controller({{#apiInfo}}{{#apis}}{{#operations}}{{classVarName}}: {{classname}}{{^-last}}, {{/-last}}{{/operations}}{{/apis}}{{/apiInfo}})(implicit system: ActorSystem, materializer: ActorMaterializer) {
lazy val routes: Route = {{#apiInfo}}{{#apis}}{{#operations}}{{classVarName}}.route {{^-last}}~ {{/-last}}{{/operations}}{{/apis}}{{/apiInfo}}
Http().newServerAt("0.0.0.0", 9000).bind(routes)
Http().bindAndHandle(routes, "0.0.0.0", 9000)
}

View File

@ -6,7 +6,6 @@ import {{akkaImportGroupId}}.http.scaladsl.server.directives.BasicDirectives
import {{akkaImportGroupId}}.http.scaladsl.unmarshalling.Unmarshaller.UnsupportedContentTypeException
import scala.concurrent.Future
import scala.language.implicitConversions
import scala.util.{Failure, Success}
trait StringDirectives {

View File

@ -140,10 +140,10 @@ export function {{classname}}ToJSONTyped(value?: {{#hasReadOnly}}Omit<{{classnam
{{^isReadOnly}}
{{#isPrimitiveType}}
{{#isDateType}}
'{{baseName}}': {{^required}}{{#isNullable}}value['{{name}}'] === null ? null : {{/isNullable}}{{^isNullable}}value['{{name}}'] == null ? undefined : {{/isNullable}}{{/required}}((value['{{name}}']{{#isNullable}} as any{{/isNullable}}){{^required}}{{#isNullable}}?{{/isNullable}}{{/required}}.toISOString().substring(0,10)),
'{{baseName}}': {{^required}}value['{{name}}'] == null ? undefined : {{/required}}({{#required}}{{#isNullable}}value['{{name}}'] == null ? null : {{/isNullable}}{{/required}}(value['{{name}}']{{#isNullable}} as any{{/isNullable}}).toISOString().substring(0,10)),
{{/isDateType}}
{{#isDateTimeType}}
'{{baseName}}': {{^required}}{{#isNullable}}value['{{name}}'] === null ? null : {{/isNullable}}{{^isNullable}}value['{{name}}'] == null ? undefined : {{/isNullable}}{{/required}}((value['{{name}}']{{#isNullable}} as any{{/isNullable}}){{^required}}{{#isNullable}}?{{/isNullable}}{{/required}}.toISOString()),
'{{baseName}}': {{^required}}value['{{name}}'] == null ? undefined : {{/required}}({{#required}}{{#isNullable}}value['{{name}}'] == null ? null : {{/isNullable}}{{/required}}(value['{{name}}']{{#isNullable}} as any{{/isNullable}}).toISOString()),
{{/isDateTimeType}}
{{#isArray}}
'{{baseName}}': {{#uniqueItems}}{{^required}}value['{{name}}'] == null ? undefined : {{/required}}{{#required}}{{#isNullable}}value['{{name}}'] == null ? null : {{/isNullable}}{{/required}}Array.from(value['{{name}}'] as Set<any>){{/uniqueItems}}{{^uniqueItems}}value['{{name}}']{{/uniqueItems}},

View File

@ -5384,37 +5384,6 @@ public class SpringCodegenTest {
JavaFileAssert.assertThat(files.get("Type.java")).fileContains("Type implements java.io.Serializable {");
}
@Test
public void givenMultipartForm_whenGenerateUsingOptional_thenParameterAreCreatedAsOptional() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
String outputPath = output.getAbsolutePath().replace('\\', '/');
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/spring/issue_9530.yaml");
final SpringCodegen codegen = new SpringCodegen();
codegen.additionalProperties().put(INTERFACE_ONLY, "true");
codegen.additionalProperties().put(SpringCodegen.USE_OPTIONAL, "true");
codegen.setOpenAPI(openAPI);
codegen.setOutputDir(output.getAbsolutePath());
ClientOptInput input = new ClientOptInput();
input.openAPI(openAPI);
input.config(codegen);
DefaultGenerator generator = new DefaultGenerator();
generator.setGenerateMetadata(false);
generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false");
generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false");
generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true");
generator.opts(input).generate();
assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/PetApi.java"),
"@Valid @RequestParam(value = \"additionalMetadata\", required = false) Optional<String> additionalMetadata",
"@Valid @RequestParam(value = \"length\", required = true) Integer length");
}
@Test
public void shouldEnableBuiltInValidationOptionWhenSetToTrue() throws IOException {
final SpringCodegen codegen = new SpringCodegen();

View File

@ -38,8 +38,5 @@ public class KotlinMiskServerCodegenOptionsTest extends AbstractOptionsTest {
verify(codegen).setAdditionalModelTypeAnnotations(List.of(KotlinMiskServerCodegenOptionsProvider.ADDITIONAL_MODEL_TYPE_ANNOTATIONS_VALUE));
verify(codegen).setUseBeanValidation(Boolean.valueOf(KotlinMiskServerCodegenOptionsProvider.USE_BEAN_VALIDATION));
verify(codegen).setModuleClassName(KotlinMiskServerCodegenOptionsProvider.MODULE_CLASS_NAME);
verify(codegen).setActionPathPrefix(KotlinMiskServerCodegenOptionsProvider.ACTION_PATH_PREFIX);
verify(codegen).setGenerateStubImplClasses(Boolean.valueOf(KotlinMiskServerCodegenOptionsProvider.GENERATE_STUB_IMPL_CLASSES));
verify(codegen).setAddModelMoshiJsonAnnotation(Boolean.valueOf(KotlinMiskServerCodegenOptionsProvider.ADD_MODEL_MOSHI_JSON_ANNOTATION));
}
}

View File

@ -33,8 +33,7 @@ public class KotlinMiskServerCodegenTest {
Assert.assertEquals(codegen.apiPackage(), "org.openapitools.server.api.api");
Assert.assertEquals(codegen.modelPackage(), "org.openapitools.server.api.model");
// Test wire formats
Assert.assertTrue(codegen.getFeatureSet().getWireFormatFeatures().contains(WireFormatFeature.JSON));
// Test PROTOBUF wire format
Assert.assertTrue(codegen.getFeatureSet().getWireFormatFeatures().contains(WireFormatFeature.PROTOBUF));
}

View File

@ -23,10 +23,7 @@ public class KotlinMiskServerCodegenOptionsProvider implements OptionsProvider {
public static final String API_SUFFIX_VALUE = "Api";
public static final String ADDITIONAL_MODEL_TYPE_ANNOTATIONS_VALUE = "";
public static final String USE_BEAN_VALIDATION = "false";
public static final String GENERATE_STUB_IMPL_CLASSES = "false";
public static final String ADD_MODEL_MOSHI_JSON_ANNOTATION = "true";
public static final String MODULE_CLASS_NAME = "OpenApiModule";
public static final String ACTION_PATH_PREFIX = "samplePrefix";
@Override
public String getLanguage() {
@ -54,9 +51,6 @@ public class KotlinMiskServerCodegenOptionsProvider implements OptionsProvider {
ADDITIONAL_MODEL_TYPE_ANNOTATIONS_VALUE)
.put(KotlinMiskServerCodegen.MODULE_CLASS_NAME, MODULE_CLASS_NAME)
.put(BeanValidationFeatures.USE_BEANVALIDATION, USE_BEAN_VALIDATION)
.put(KotlinMiskServerCodegen.ACTION_PATH_PREFIX, ACTION_PATH_PREFIX)
.put(KotlinMiskServerCodegen.ADD_MODEL_MOSHI_JSON_ANNOTATION, ADD_MODEL_MOSHI_JSON_ANNOTATION)
.put(KotlinMiskServerCodegen.GENERATE_STUB_IMPL_CLASSES, GENERATE_STUB_IMPL_CLASSES)
.build();
}

View File

@ -117,34 +117,6 @@ paths:
security:
- petstore_auth:
- 'read:pets'
/pet/findByColor:
get:
tags:
- pet
summary: Finds Pets by color
description: Returns pets filtered by color.
operationId: findPetsByColor
parameters:
- name: color
in: query
description: Color of the pet to filter by
required: false
schema:
$ref: '#/components/schemas/Color'
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid color value
security:
- petstore_auth:
- 'read:pets'
/pet/findByTags:
get:
tags:
@ -776,18 +748,6 @@ components:
- sold
xml:
name: Pet
Color:
title: Pet Color
description: pet color in the store
type: string
enum:
- black
- white
- brown
- golden
- mixed
xml:
name: Pet
ApiResponse:
title: An uploaded response
description: Describes the result of uploading an image resource

View File

@ -1,75 +0,0 @@
openapi: 3.0.1
info:
version: "1.0.0"
title: use-optional-multipart-spring-boot-request-body-issue
paths:
/pet/{petId}/uploadImage:
post:
tags:
- pet tag
summary: uploads an image
operationId: uploadFile
parameters:
- name: petId
in: path
description: ID of pet to update
required: true
schema:
type: integer
format: int64
requestBody:
content:
multipart/form-data:
schema:
required:
- length
properties:
additionalMetadata:
type: string
description: Additional data to pass to server
length:
type: integer
description: Content length
file:
type: string
description: file to upload
format: binary
responses:
200:
description: successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
security:
- petstore_auth:
- write:pets
- read:pets
components:
schemas:
ApiResponse:
title: An uploaded response
type: object
properties:
code:
type: integer
format: int32
type:
type: string
message:
type: string
description: Describes the result of uploading an image resource
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

View File

@ -15,7 +15,7 @@
<packaging>pom</packaging>
<name>openapi-generator-project</name>
<!-- RELEASE_VERSION -->
<version>7.14.0-SNAPSHOT</version>
<version>7.13.0</version>
<!-- /RELEASE_VERSION -->
<url>https://github.com/openapitools/openapi-generator</url>
<scm>

View File

@ -1 +1 @@
7.14.0-SNAPSHOT
7.13.0-SNAPSHOT

View File

@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [OpenAPI Generator](https://openap
- API version: 0.1.0
- SDK version: 1.0.0
- Generator version: 7.14.0-SNAPSHOT
- Generator version: 7.13.0-SNAPSHOT
- Build package: org.openapitools.codegen.languages.CSharpClientCodegen
<a id="frameworks-supported"></a>

View File

@ -1 +1 @@
7.14.0-SNAPSHOT
7.13.0-SNAPSHOT

View File

@ -7,7 +7,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat
- API version: 0.1.0
- Package version: 1.0.0
- Generator version: 7.14.0-SNAPSHOT
- Generator version: 7.13.0-SNAPSHOT
- Build package: org.openapitools.codegen.languages.GoClientCodegen
## Installation

View File

@ -1 +1 @@
7.14.0-SNAPSHOT
7.13.0-SNAPSHOT

View File

@ -7,7 +7,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat
- API version: 0.1.0
- Package version: 1.0.0
- Generator version: 7.14.0-SNAPSHOT
- Generator version: 7.13.0-SNAPSHOT
- Build package: org.openapitools.codegen.languages.GoClientCodegen
## Installation

View File

@ -1 +1 @@
7.14.0-SNAPSHOT
7.13.0-SNAPSHOT

View File

@ -4,7 +4,7 @@ Echo Server API
- API version: 0.1.0
- Generator version: 7.14.0-SNAPSHOT
- Generator version: 7.13.0-SNAPSHOT
Echo Server API

View File

@ -81,7 +81,7 @@ import org.openapitools.client.auth.Authentication;
import org.openapitools.client.auth.HttpBasicAuth;
import org.openapitools.client.auth.HttpBearerAuth;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class ApiClient extends JavaTimeFormatter {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map<String, String> defaultCookieMap = new HashMap<String, String>();

View File

@ -16,7 +16,7 @@ package org.openapitools.client;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class ApiException extends Exception {
private static final long serialVersionUID = 1L;

View File

@ -17,7 +17,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import java.util.Collections;
import java.util.Map;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public abstract class BaseApi {
protected ApiClient apiClient;

View File

@ -17,7 +17,7 @@ import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class Configuration {
public static final String VERSION = "0.1.0";

View File

@ -20,7 +20,7 @@ import java.time.format.DateTimeParseException;
* Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class.
* It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}.
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class JavaTimeFormatter {
private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

View File

@ -13,7 +13,7 @@
package org.openapitools.client;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class Pair {
private String name = "";
private String value = "";

View File

@ -22,7 +22,7 @@ import java.text.DecimalFormat;
import java.util.GregorianCalendar;
import java.util.TimeZone;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class RFC3339DateFormat extends DateFormat {
private static final long serialVersionUID = 1L;
private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC");

View File

@ -28,7 +28,7 @@ import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeFeature;
import com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class RFC3339InstantDeserializer<T extends Temporal> extends InstantDeserializer<T> {
private final static boolean DEFAULT_NORMALIZE_ZONE_ID = JavaTimeFeature.NORMALIZE_DESERIALIZED_ZONE_ID.enabledByDefault();

View File

@ -18,7 +18,7 @@ import java.time.ZonedDateTime;
import com.fasterxml.jackson.databind.module.SimpleModule;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class RFC3339JavaTimeModule extends SimpleModule {
public RFC3339JavaTimeModule() {

View File

@ -18,7 +18,7 @@ import java.util.Map;
/**
* Representing a Server configuration.
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class ServerConfiguration {
public String URL;
public String description;

View File

@ -18,7 +18,7 @@ import java.util.HashSet;
/**
* Representing a Server Variable for server URL template substitution.
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class ServerVariable {
public String description;
public String defaultValue;

View File

@ -16,7 +16,7 @@ package org.openapitools.client;
import java.util.Collection;
import java.util.Iterator;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).

View File

@ -29,7 +29,7 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class AuthApi extends BaseApi {
public AuthApi() {

View File

@ -33,7 +33,7 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class BodyApi extends BaseApi {
public BodyApi() {

View File

@ -30,7 +30,7 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class FormApi extends BaseApi {
public FormApi() {

View File

@ -30,7 +30,7 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class HeaderApi extends BaseApi {
public HeaderApi() {

View File

@ -30,7 +30,7 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class PathApi extends BaseApi {
public PathApi() {

View File

@ -36,7 +36,7 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class QueryApi extends BaseApi {
public QueryApi() {

View File

@ -18,7 +18,7 @@ import org.openapitools.client.Pair;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;

View File

@ -18,7 +18,7 @@ import org.openapitools.client.Pair;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public interface Authentication {
/**
* Apply authentication settings to header and query params.

View File

@ -21,7 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class HttpBasicAuth implements Authentication {
private String username;
private String password;

View File

@ -20,7 +20,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class HttpBearerAuth implements Authentication {
private final String scheme;
private Supplier<String> tokenSupplier;

View File

@ -33,7 +33,7 @@ import java.util.StringJoiner;
Bird.JSON_PROPERTY_SIZE,
Bird.JSON_PROPERTY_COLOR
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class Bird {
public static final String JSON_PROPERTY_SIZE = "size";
@javax.annotation.Nullable

View File

@ -33,7 +33,7 @@ import java.util.StringJoiner;
Category.JSON_PROPERTY_ID,
Category.JSON_PROPERTY_NAME
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class Category {
public static final String JSON_PROPERTY_ID = "id";
@javax.annotation.Nullable

View File

@ -39,7 +39,7 @@ import java.util.StringJoiner;
DataQuery.JSON_PROPERTY_TEXT,
DataQuery.JSON_PROPERTY_DATE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class DataQuery extends Query {
public static final String JSON_PROPERTY_SUFFIX = "suffix";
@javax.annotation.Nullable

View File

@ -47,7 +47,7 @@ import java.util.StringJoiner;
DefaultValue.JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE,
DefaultValue.JSON_PROPERTY_STRING_NULLABLE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class DefaultValue {
public static final String JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT = "array_string_enum_ref_default";
@javax.annotation.Nullable

View File

@ -35,7 +35,7 @@ import java.util.StringJoiner;
NumberPropertiesOnly.JSON_PROPERTY_FLOAT,
NumberPropertiesOnly.JSON_PROPERTY_DOUBLE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class NumberPropertiesOnly {
public static final String JSON_PROPERTY_NUMBER = "number";
@javax.annotation.Nullable

View File

@ -42,7 +42,7 @@ import java.util.StringJoiner;
Pet.JSON_PROPERTY_TAGS,
Pet.JSON_PROPERTY_STATUS
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class Pet {
public static final String JSON_PROPERTY_ID = "id";
@javax.annotation.Nullable

View File

@ -36,7 +36,7 @@ import java.util.StringJoiner;
Query.JSON_PROPERTY_ID,
Query.JSON_PROPERTY_OUTCOMES
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class Query {
public static final String JSON_PROPERTY_ID = "id";
@javax.annotation.Nullable

View File

@ -33,7 +33,7 @@ import java.util.StringJoiner;
Tag.JSON_PROPERTY_ID,
Tag.JSON_PROPERTY_NAME
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class Tag {
public static final String JSON_PROPERTY_ID = "id";
@javax.annotation.Nullable

View File

@ -33,7 +33,7 @@ import java.util.StringJoiner;
TestFormObjectMultipartRequestMarker.JSON_PROPERTY_NAME
})
@JsonTypeName("test_form_object_multipart_request_marker")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.14.0-SNAPSHOT")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.13.0-SNAPSHOT")
public class TestFormObjectMultipartRequestMarker {
public static final String JSON_PROPERTY_NAME = "name";
@javax.annotation.Nullable

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