Merge remote-tracking branch 'origin/5.3.x' into 6.0.x

This commit is contained in:
William Cheng 2021-07-27 11:52:19 +08:00
commit b799ca9ee0
1011 changed files with 34058 additions and 5848 deletions

View File

@ -16,5 +16,5 @@
These must match the expectations made by your contribution. These must match the expectations made by your contribution.
You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example `./bin/generate-samples.sh bin/configs/java*`. You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example `./bin/generate-samples.sh bin/configs/java*`.
For Windows users, please run the script in [Git BASH](https://gitforwindows.org/). For Windows users, please run the script in [Git BASH](https://gitforwindows.org/).
- [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `5.1.x`, `6.0.x` - [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `5.3.x`, `6.0.x`
- [ ] If your PR is targeting a particular programming language, @mention the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) members, so they are more likely to review the pull request. - [ ] If your PR is targeting a particular programming language, @mention the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) members, so they are more likely to review the pull request.

View File

@ -826,6 +826,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2021-04-27 - [From zero to publishing PowerShell API clients in PowerShell Gallery within minutes](https://speakerdeck.com/wing328/from-zero-to-publishing-powershell-api-clients-in-powershell-gallery-within-minutes) by [William Cheng](https://github.com/wing328) at [PowerShell + DevOps Global Summit 2021](https://events.devopscollective.org/event/powershell-devops-global-summit-2021/) - 2021-04-27 - [From zero to publishing PowerShell API clients in PowerShell Gallery within minutes](https://speakerdeck.com/wing328/from-zero-to-publishing-powershell-api-clients-in-powershell-gallery-within-minutes) by [William Cheng](https://github.com/wing328) at [PowerShell + DevOps Global Summit 2021](https://events.devopscollective.org/event/powershell-devops-global-summit-2021/)
- 2021-05-31 - [FlutterでOpen Api Generator(Swagger)を使う](https://aakira.app/blog/2021/05/flutter-open-api/) by [AAkira](https://twitter.com/_a_akira) - 2021-05-31 - [FlutterでOpen Api Generator(Swagger)を使う](https://aakira.app/blog/2021/05/flutter-open-api/) by [AAkira](https://twitter.com/_a_akira)
- 2021-06-22 - [Rest API Documentation and Client Generation With OpenAPI](https://dzone.com/articles/rest-api-documentation-and-client-generation-with) by [Prasanth Gullapalli](https://dzone.com/users/1011797/prasanthnath.g@gmail.com.html) - 2021-06-22 - [Rest API Documentation and Client Generation With OpenAPI](https://dzone.com/articles/rest-api-documentation-and-client-generation-with) by [Prasanth Gullapalli](https://dzone.com/users/1011797/prasanthnath.g@gmail.com.html)
- 2021-07-16 - [銀行事業のサーバーサイド開発について / LINE 京都開発室 エンジニア採用説明会](https://www.youtube.com/watch?v=YrrKQHxLPpQ) by 野田誠人, Robert Mitchell
## [6 - About Us](#table-of-contents) ## [6 - About Us](#table-of-contents)
@ -1029,7 +1030,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| C++ | @ravinikam (2017/07) @stkrwork (2017/07) @etherealjoy (2018/02) @martindelille (2018/03) @muttleyxd (2019/08) | | C++ | @ravinikam (2017/07) @stkrwork (2017/07) @etherealjoy (2018/02) @martindelille (2018/03) @muttleyxd (2019/08) |
| C# | @mandrean (2017/08) @frankyjuang (2019/09) @shibayan (2020/02) @Blackclaws (2021/03) @lucamazzanti (2021/05) | | C# | @mandrean (2017/08) @frankyjuang (2019/09) @shibayan (2020/02) @Blackclaws (2021/03) @lucamazzanti (2021/05) |
| Clojure | | | Clojure | |
| Dart | @swipesight (2018/09) @jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) | | Dart | @jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) |
| Eiffel | @jvelilla (2017/09) | | Eiffel | @jvelilla (2017/09) |
| Elixir | @mrmstn (2018/12) | | Elixir | @mrmstn (2018/12) |
| Elm | @eriktim (2018/09) | | Elm | @eriktim (2018/09) |

View File

@ -1,7 +1,7 @@
generatorName: java generatorName: java
outputDir: samples/client/petstore/java/feign outputDir: samples/client/petstore/java/feign
library: feign library: feign
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/Java templateDir: modules/openapi-generator/src/main/resources/Java
additionalProperties: additionalProperties:
booleanGetterPrefix: is booleanGetterPrefix: is

View File

@ -1,11 +0,0 @@
generatorName: java
outputDir: samples/openapi3/client/petstore/java/native
library: native
inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/Java
additionalProperties:
artifactId: petstore-openapi3-native
hideGenerationTimestamp: true
serverPort: "8082"
useOneOfDiscriminatorLookup: true
disallowAdditionalPropertiesIfNotPresent: false

View File

@ -3,6 +3,7 @@ outputDir: samples/client/petstore/java/resttemplate-withXml
library: resttemplate library: resttemplate
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
additionalProperties: additionalProperties:
java8: true
withXml: "true" withXml: "true"
artifactId: petstore-resttemplate-withxml artifactId: petstore-resttemplate-withxml
hideGenerationTimestamp: "true" hideGenerationTimestamp: "true"

View File

@ -5,3 +5,4 @@ inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-e
additionalProperties: additionalProperties:
artifactId: petstore-resttemplate artifactId: petstore-resttemplate
hideGenerationTimestamp: "true" hideGenerationTimestamp: "true"
java8: true

View File

@ -1,7 +1,7 @@
generatorName: java generatorName: java
outputDir: samples/client/petstore/java/webclient outputDir: samples/client/petstore/java/webclient
library: webclient library: webclient
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
additionalProperties: additionalProperties:
artifactId: petstore-webclient artifactId: petstore-webclient
hideGenerationTimestamp: "true" hideGenerationTimestamp: "true"

View File

@ -0,0 +1,6 @@
generatorName: jaxrs-cxf-client
outputDir: samples/openapi3/client/petstore/jaxrs-cxf-client-jackson-nullable
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaJaxRS/cxf
additionalProperties:
jackson: "true"

View File

@ -1,7 +1,7 @@
generatorName: rust generatorName: rust
outputDir: samples/client/petstore/rust/hyper/petstore outputDir: samples/client/petstore/rust/hyper/petstore
library: hyper library: hyper
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/rust templateDir: modules/openapi-generator/src/main/resources/rust
additionalProperties: additionalProperties:
supportAsync: "false" supportAsync: "false"

View File

@ -1,7 +1,7 @@
generatorName: rust generatorName: rust
outputDir: samples/client/petstore/rust/reqwest/petstore-async outputDir: samples/client/petstore/rust/reqwest/petstore-async
library: reqwest library: reqwest
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/rust templateDir: modules/openapi-generator/src/main/resources/rust
additionalProperties: additionalProperties:
supportAsync: true supportAsync: true

View File

@ -1,7 +1,7 @@
generatorName: rust generatorName: rust
outputDir: samples/client/petstore/rust/reqwest/petstore outputDir: samples/client/petstore/rust/reqwest/petstore
library: reqwest library: reqwest
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/rust templateDir: modules/openapi-generator/src/main/resources/rust
additionalProperties: additionalProperties:
supportAsync: false supportAsync: false

View File

@ -238,7 +238,7 @@
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
<kotlin.version>1.5.10</kotlin.version> <kotlin.version>1.5.10</kotlin.version>
<kotlinJvmTarget>1.8</kotlinJvmTarget> <kotlinJvmTarget>1.8</kotlinJvmTarget>
<moshi-kotlin.version>1.8.0</moshi-kotlin.version> <moshi-kotlin.version>1.12.0</moshi-kotlin.version>
<migbase64.version>2.2</migbase64.version> <migbase64.version>2.2</migbase64.version>
</properties> </properties>
</project> </project>

View File

@ -301,7 +301,7 @@ public class CodegenConfigurator {
public CodegenConfigurator setGitUserId(String gitUserId) { public CodegenConfigurator setGitUserId(String gitUserId) {
if (StringUtils.isNotEmpty(gitUserId)) { if (StringUtils.isNotEmpty(gitUserId)) {
addAdditionalProperty(CodegenConstants.GIT_HOST, gitUserId); addAdditionalProperty(CodegenConstants.GIT_USER_ID, gitUserId);
} }
generatorSettingsBuilder.withGitUserId(gitUserId); generatorSettingsBuilder.withGitUserId(gitUserId);
return this; return this;

View File

@ -1263,6 +1263,19 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
} }
} }
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
// ensure a method's parameters are marked as nullable when nullable or when nullReferences are enabled
// this is mostly needed for reference types used as a method's parameters
if (!parameter.required && (nullReferenceTypesFlag || nullableType.contains(parameter.dataType))) {
parameter.dataType = parameter.dataType.endsWith("?")
? parameter.dataType
: parameter.dataType + "?";
}
}
@Override @Override
public void postProcessFile(File file, String fileType) { public void postProcessFile(File file, String fileType) {
if (file == null) { if (file == null) {

View File

@ -70,6 +70,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public static final String ADDITIONAL_ENUM_TYPE_ANNOTATIONS = "additionalEnumTypeAnnotations"; public static final String ADDITIONAL_ENUM_TYPE_ANNOTATIONS = "additionalEnumTypeAnnotations";
public static final String DISCRIMINATOR_CASE_SENSITIVE = "discriminatorCaseSensitive"; public static final String DISCRIMINATOR_CASE_SENSITIVE = "discriminatorCaseSensitive";
public static final String OPENAPI_NULLABLE = "openApiNullable"; public static final String OPENAPI_NULLABLE = "openApiNullable";
public static final String JACKSON = "jackson";
protected String dateLibrary = "threetenbp"; protected String dateLibrary = "threetenbp";
protected boolean supportAsync = false; protected boolean supportAsync = false;
@ -525,6 +526,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue"); importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue");
importMapping.put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore"); importMapping.put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore");
importMapping.put("JsonInclude", "com.fasterxml.jackson.annotation.JsonInclude"); importMapping.put("JsonInclude", "com.fasterxml.jackson.annotation.JsonInclude");
importMapping.put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable");
importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName"); importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName");
importMapping.put("TypeAdapter", "com.google.gson.TypeAdapter"); importMapping.put("TypeAdapter", "com.google.gson.TypeAdapter");
importMapping.put("JsonAdapter", "com.google.gson.annotations.JsonAdapter"); importMapping.put("JsonAdapter", "com.google.gson.annotations.JsonAdapter");
@ -1174,7 +1176,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (codegenModel.description != null) { if (codegenModel.description != null) {
codegenModel.imports.add("ApiModel"); codegenModel.imports.add("ApiModel");
} }
if (codegenModel.discriminator != null && additionalProperties.containsKey("jackson")) { if (codegenModel.discriminator != null && additionalProperties.containsKey(JACKSON)) {
codegenModel.imports.add("JsonSubTypes"); codegenModel.imports.add("JsonSubTypes");
codegenModel.imports.add("JsonTypeInfo"); codegenModel.imports.add("JsonTypeInfo");
} }

View File

@ -70,7 +70,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
additionalProperties.put("title", title); additionalProperties.put("title", title);
// java inflector uses the jackson lib // java inflector uses the jackson lib
additionalProperties.put("jackson", "true"); additionalProperties.put(JACKSON, "true");
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC).defaultValue(implFolder)); cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC).defaultValue(implFolder));
cliOptions.add(new CliOption("title", "a title describing the application").defaultValue(title)); cliOptions.add(new CliOption("title", "a title describing the application").defaultValue(title));

View File

@ -17,6 +17,7 @@
package org.openapitools.codegen.languages; package org.openapitools.codegen.languages;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.media.StringSchema;
@ -928,6 +929,24 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "URI.create('" + p.getDefault() + "')"; return "URI.create('" + p.getDefault() + "')";
} }
} else if (ModelUtils.isArraySchema(p)) {
if (p.getDefault() != null) {
String arrInstantiationType = ModelUtils.isSet(p) ? "set" : "arrayList";
ArrayNode _default = (ArrayNode) p.getDefault();
if (_default.isEmpty()) {
return arrInstantiationType + "Of()";
}
StringBuilder defaultContent = new StringBuilder();
Schema<?> itemsSchema = getSchemaItems((ArraySchema) schema);
_default.elements().forEachRemaining((element) -> {
itemsSchema.setDefault(element.asText());
defaultContent.append(toDefaultValue(itemsSchema)).append(",");
});
defaultContent.deleteCharAt(defaultContent.length()-1); // remove trailing comma
return arrInstantiationType + "Of(" + defaultContent + ")";
}
} else if (ModelUtils.isStringSchema(p)) { } else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
String _default = (String) p.getDefault(); String _default = (String) p.getDefault();

View File

@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import static org.openapitools.codegen.utils.StringUtils.camelize; import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore; import static org.openapitools.codegen.utils.StringUtils.underscore;
@ -190,6 +191,18 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
this.setParameterNamingConvention((String) additionalProperties.get(VARIABLE_NAMING_CONVENTION)); this.setParameterNamingConvention((String) additionalProperties.get(VARIABLE_NAMING_CONVENTION));
} }
if (additionalProperties.containsKey(CodegenConstants.GIT_USER_ID)) {
this.setGitUserId((String) additionalProperties.get(CodegenConstants.GIT_USER_ID));
}
if (additionalProperties.containsKey(CodegenConstants.GIT_REPO_ID)) {
this.setGitRepoId((String) additionalProperties.get(CodegenConstants.GIT_REPO_ID));
}
if (!this.getComposerPackageName().isEmpty()) {
additionalProperties.put("composerPackageName", this.getComposerPackageName());
}
additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\"));
// make api and model src path available in mustache template // make api and model src path available in mustache template
@ -758,4 +771,22 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
} }
} }
} }
/**
* Get Composer package name based on GIT_USER_ID and GIT_REPO_ID.
*
* @return package name or empty string on fail
*/
public String getComposerPackageName() {
String packageName = this.getGitUserId() + "/" + this.getGitRepoId();
if (
packageName.contentEquals("/")
|| packageName.contentEquals("null/null")
|| !Pattern.matches("^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$", packageName)
) {
return "";
}
return packageName;
}
} }

View File

@ -536,33 +536,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
return this.modelPropertyNaming; return this.modelPropertyNaming;
} }
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
super.postProcessOperationsWithModels(objs, allModels);
if (objs != null) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.returnType != null) {
operation.returnContainer = operation.returnType;
if (this.returnICollection && (
operation.returnType.startsWith("List") ||
operation.returnType.startsWith("Collection"))) {
// NOTE: ICollection works for both List<T> and Collection<T>
int genericStart = operation.returnType.indexOf("<");
if (genericStart > 0) {
operation.returnType = "ICollection" + operation.returnType.substring(genericStart);
}
}
}
}
}
}
return objs;
}
@Override @Override
public CodegenType getTag() { public CodegenType getTag() {
return CodegenType.CLIENT; return CodegenType.CLIENT;

View File

@ -468,33 +468,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
super.postProcessModelProperty(model, property); super.postProcessModelProperty(model, property);
} }
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
super.postProcessOperationsWithModels(objs, allModels);
if (objs != null) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.returnType != null) {
operation.returnContainer = operation.returnType;
if (this.returnICollection && (
operation.returnType.startsWith("List") ||
operation.returnType.startsWith("Collection"))) {
// NOTE: ICollection works for both List<T> and Collection<T>
int genericStart = operation.returnType.indexOf("<");
if (genericStart > 0) {
operation.returnType = "ICollection" + operation.returnType.substring(genericStart);
}
}
}
}
}
}
return objs;
}
@Override @Override
public void postProcessParameter(CodegenParameter parameter) { public void postProcessParameter(CodegenParameter parameter) {
postProcessPattern(parameter.pattern, parameter.vendorExtensions); postProcessPattern(parameter.pattern, parameter.vendorExtensions);

View File

@ -157,6 +157,7 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
final String authFolder = srcFolder + File.separator + "auth"; final String authFolder = srcFolder + File.separator + "auth";
supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart"));
supportingFiles.add(new SupportingFile("auth/basic_auth.mustache", authFolder, "basic_auth.dart")); supportingFiles.add(new SupportingFile("auth/basic_auth.mustache", authFolder, "basic_auth.dart"));
supportingFiles.add(new SupportingFile("auth/bearer_auth.mustache", authFolder, "bearer_auth.dart"));
supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart")); supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart"));
supportingFiles.add(new SupportingFile("auth/auth.mustache", authFolder, "auth.dart")); supportingFiles.add(new SupportingFile("auth/auth.mustache", authFolder, "auth.dart"));
@ -322,6 +323,18 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
} }
} }
// the MultipartFile handling above changes the type of some parameters from
// `UInt8List`, the default for files, to `MultipartFile`.
//
// The following block removes the required import for Uint8List if it is no
// longer in use.
if (op.allParams.stream().noneMatch(param -> param.dataType.equals("Uint8List"))
&& op.responses.stream().filter(response -> response.dataType != null)
.noneMatch(response -> response.dataType.equals("Uint8List"))) {
// Remove unused imports after processing
op.imports.remove("Uint8List");
}
for (CodegenParameter param : op.bodyParams) { for (CodegenParameter param : op.bodyParams) {
if (param.isContainer) { if (param.isContainer) {
final Map<String, Object> serializer = new HashMap<>(); final Map<String, Object> serializer = new HashMap<>();
@ -333,11 +346,6 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
} }
} }
if (op.allParams.stream().noneMatch(param -> param.dataType.equals("Uint8List"))) {
// Remove unused imports after processing
op.imports.remove("Uint8List");
}
resultImports.addAll(rewriteImports(op.imports, false)); resultImports.addAll(rewriteImports(op.imports, false));
if (op.getHasFormParams() || op.getHasQueryParams()) { if (op.getHasFormParams() || op.getHasQueryParams()) {
resultImports.add("package:" + pubName + "/src/api_util.dart"); resultImports.add("package:" + pubName + "/src/api_util.dart");

View File

@ -879,15 +879,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
private void processReturnType(CodegenOperation op) { private void processReturnType(CodegenOperation op) {
String returnType = op.returnType; String returnType = op.returnType;
if (returnType == null || returnType.equals("null")) { if (returnType == null || returnType.equals("null")) {
if (op.hasProduces) { returnType = "NoContent";
returnType = "res"; SetNoContent(op, VENDOR_EXTENSION_X_INLINE_ACCEPT);
op.vendorExtensions.put(VENDOR_EXTENSION_X_HAS_UNKNOWN_RETURN, true);
} else {
returnType = "NoContent";
if (!op.vendorExtensions.containsKey(VENDOR_EXTENSION_X_INLINE_ACCEPT)) {
SetNoContent(op, VENDOR_EXTENSION_X_INLINE_ACCEPT);
}
}
} }
if (returnType.contains(" ")) { if (returnType.contains(" ")) {
returnType = "(" + returnType + ")"; returnType = "(" + returnType + ")";

View File

@ -49,6 +49,8 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
protected boolean useLoggingFeatureForTests = false; protected boolean useLoggingFeatureForTests = false;
private boolean useJackson = false;
public JavaCXFClientCodegen() { public JavaCXFClientCodegen() {
super(); super();
@ -108,6 +110,10 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS)); this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS));
} }
if (additionalProperties.containsKey(JACKSON)) {
useJackson = convertPropertyToBooleanAndWriteBack(JACKSON);
}
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml") supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")
@ -139,12 +145,22 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
model.imports.remove("JsonSerialize"); model.imports.remove("JsonSerialize");
model.imports.remove("ToStringSerializer"); model.imports.remove("ToStringSerializer");
//Add imports for Jackson when model has inner enum
if (additionalProperties.containsKey("jackson")) { if (useJackson) {
//Add jackson imports when model has inner enum
if (Boolean.FALSE.equals(model.isEnum) && Boolean.TRUE.equals(model.hasEnums)) { if (Boolean.FALSE.equals(model.isEnum) && Boolean.TRUE.equals(model.hasEnums)) {
model.imports.add("JsonCreator"); model.imports.add("JsonCreator");
model.imports.add("JsonValue"); model.imports.add("JsonValue");
} }
//Add JsonNullable import and mark property nullable for templating if necessary
if (openApiNullable) {
if (Boolean.FALSE.equals(property.required) && Boolean.TRUE.equals(property.isNullable)) {
property.getVendorExtensions().put("x-is-jackson-optional-nullable", true);
model.imports.add("JsonNullable");
model.imports.add("JsonIgnore");
}
}
} }
} }
@ -195,4 +211,7 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
return useGenericResponse; return useGenericResponse;
} }
public boolean isUseJackson() {
return useJackson;
}
} }

View File

@ -242,7 +242,7 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
model.imports.remove("ToStringSerializer"); model.imports.remove("ToStringSerializer");
//Add imports for Jackson when model has inner enum //Add imports for Jackson when model has inner enum
if (additionalProperties.containsKey("jackson")) { if (additionalProperties.containsKey(JACKSON)) {
if (Boolean.FALSE.equals(model.isEnum) && Boolean.TRUE.equals(model.hasEnums)) { if (Boolean.FALSE.equals(model.isEnum) && Boolean.TRUE.equals(model.hasEnums)) {
model.imports.add("JsonCreator"); model.imports.add("JsonCreator");
model.imports.add("JsonValue"); model.imports.add("JsonValue");

View File

@ -69,7 +69,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
additionalProperties.put("title", title); additionalProperties.put("title", title);
// java inflector uses the jackson lib // java inflector uses the jackson lib
additionalProperties.put("jackson", "true"); additionalProperties.put(JACKSON, "true");
} }
@Override @Override

View File

@ -31,7 +31,6 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen {
public static final String RETURN_RESPONSE = "returnResponse"; public static final String RETURN_RESPONSE = "returnResponse";
public static final String GENERATE_POM = "generatePom"; public static final String GENERATE_POM = "generatePom";
public static final String USE_SWAGGER_ANNOTATIONS = "useSwaggerAnnotations"; public static final String USE_SWAGGER_ANNOTATIONS = "useSwaggerAnnotations";
public static final String JACKSON = "jackson";
public static final String OPEN_API_SPEC_FILE_LOCATION = "openApiSpecFileLocation"; public static final String OPEN_API_SPEC_FILE_LOCATION = "openApiSpecFileLocation";
public static final String GENERATE_BUILDERS = "generateBuilders"; public static final String GENERATE_BUILDERS = "generateBuilders";

View File

@ -70,7 +70,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
updateOption(CodegenConstants.API_PACKAGE, apiPackage); updateOption(CodegenConstants.API_PACKAGE, apiPackage);
updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage); updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage);
additionalProperties.put("jackson", "true"); additionalProperties.put(JACKSON, "true");
this.cliOptions.add(new CliOption("basePackage", "base package for java source code")); this.cliOptions.add(new CliOption("basePackage", "base package for java source code"));
this.cliOptions.add(new CliOption("serviceName", "Service Name")); this.cliOptions.add(new CliOption("serviceName", "Service Name"));
@ -422,7 +422,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
} }
} else { // enum class } else { // enum class
// Needed imports for Jackson's JsonCreator // Needed imports for Jackson's JsonCreator
if (this.additionalProperties.containsKey("jackson")) { if (this.additionalProperties.containsKey(JACKSON)) {
model.imports.add("JsonCreator"); model.imports.add("JsonCreator");
} }
} }

View File

@ -82,7 +82,7 @@ public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements Bea
updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage); updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage);
additionalProperties.put("java8", true); additionalProperties.put("java8", true);
additionalProperties.put("jackson", "true"); additionalProperties.put(JACKSON, "true");
cliOptions.add(new CliOption(TITLE, "server title name or client service name").defaultValue(title)); cliOptions.add(new CliOption(TITLE, "server title name or client service name").defaultValue(title));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code").defaultValue(getConfigPackage())); cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code").defaultValue(getConfigPackage()));

View File

@ -574,6 +574,8 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
public String toEnumValue(String value, String datatype) { public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "float".equals(datatype)) { if ("int".equals(datatype) || "float".equals(datatype)) {
return value; return value;
} else if ("bool".equals(datatype)) {
return value.substring(0, 1).toUpperCase(Locale.ROOT) + value.substring(1);
} else { } else {
return ensureQuotes(value); return ensureQuotes(value);
} }

View File

@ -145,7 +145,7 @@ public class SpringCodegen extends AbstractJavaCodegen
apiTestTemplateFiles.clear(); // TODO: add test template apiTestTemplateFiles.clear(); // TODO: add test template
// spring uses the jackson lib // spring uses the jackson lib
additionalProperties.put("jackson", "true"); additionalProperties.put(JACKSON, "true");
additionalProperties.put("openbrace", OPEN_BRACE); additionalProperties.put("openbrace", OPEN_BRACE);
additionalProperties.put("closebrace", CLOSE_BRACE); additionalProperties.put("closebrace", CLOSE_BRACE);
@ -829,7 +829,7 @@ public class SpringCodegen extends AbstractJavaCodegen
} }
} else { // enum class } else { // enum class
//Needed imports for Jackson's JsonCreator //Needed imports for Jackson's JsonCreator
if (additionalProperties.containsKey("jackson")) { if (additionalProperties.containsKey(JACKSON)) {
model.imports.add("JsonCreator"); model.imports.add("JsonCreator");
} }
} }

View File

@ -99,7 +99,7 @@ end:
// //
{{/notes}} {{/notes}}
{{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}}
{{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}} {{/allParams}}) {{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}} {{/allParams}})
{ {
list_t *localVarQueryParameters = {{#hasQueryParams}}list_create();{{/hasQueryParams}}{{^hasQueryParams}}NULL;{{/hasQueryParams}} list_t *localVarQueryParameters = {{#hasQueryParams}}list_create();{{/hasQueryParams}}{{^hasQueryParams}}NULL;{{/hasQueryParams}}
list_t *localVarHeaderParameters = {{#hasHeaderParams}}list_create();{{/hasHeaderParams}}{{^hasHeaderParams}}NULL;{{/hasHeaderParams}} list_t *localVarHeaderParameters = {{#hasHeaderParams}}list_create();{{/hasHeaderParams}}{{^hasHeaderParams}}NULL;{{/hasHeaderParams}}
@ -194,7 +194,7 @@ end:
// header parameters // header parameters
char *keyHeader_{{{paramName}}} = NULL; char *keyHeader_{{{paramName}}} = NULL;
{{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueHeader_{{{paramName}}} = 0; {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueHeader_{{{paramName}}} = 0;
keyValuePair_t *keyPairHeader_{{paramName}} = 0; keyValuePair_t *keyPairHeader_{{paramName}} = 0;
if ({{paramName}}) { if ({{paramName}}) {
keyHeader_{{{paramName}}} = strdup("{{{baseName}}}"); keyHeader_{{{paramName}}} = strdup("{{{baseName}}}");
@ -209,7 +209,7 @@ end:
// query parameters // query parameters
{{^isArray}} {{^isArray}}
char *keyQuery_{{{paramName}}} = NULL; char *keyQuery_{{{paramName}}} = NULL;
{{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}char *{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}char *{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueQuery_{{{paramName}}} {{#isString}}{{^isEnum}}= NULL{{/isEnum}}{{/isString}}{{#isInteger}}= NULL{{/isInteger}}{{#isBoolean}}= NULL{{/isBoolean}}; {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}char *{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}char *{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueQuery_{{{paramName}}} {{#isString}}{{^isEnum}}= NULL{{/isEnum}}{{/isString}}{{#isInteger}}= NULL{{/isInteger}}{{#isBoolean}}= NULL{{/isBoolean}};
keyValuePair_t *keyPairQuery_{{paramName}} = 0; keyValuePair_t *keyPairQuery_{{paramName}} = 0;
{{/isArray}} {{/isArray}}
if ({{paramName}}) if ({{paramName}})
@ -248,7 +248,7 @@ end:
{{/isFile}} {{/isFile}}
{{^isFile}} {{^isFile}}
char *keyForm_{{paramName}} = NULL; char *keyForm_{{paramName}} = NULL;
{{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueForm_{{paramName}} = 0; {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueForm_{{paramName}} = 0;
keyValuePair_t *keyPairForm_{{paramName}} = 0; keyValuePair_t *keyPairForm_{{paramName}} = 0;
{{/isFile}} {{/isFile}}
if ({{paramName}} != NULL) if ({{paramName}} != NULL)

View File

@ -33,7 +33,7 @@ typedef enum { {{projectName}}_{{operationId}}_{{enumName}}_NULL = 0{{#enumVars
// //
{{/notes}} {{/notes}}
{{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}}
{{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}} {{/allParams}}); {{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}} {{/allParams}});
{{/operation}} {{/operation}}

View File

@ -20,7 +20,7 @@ Method | HTTP request | Description
// {{{notes}}} // {{{notes}}}
// //
{{/notes}} {{/notes}}
{{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} {{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}}{{/allParams}}); {{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} {{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}}{{/allParams}});
``` ```
### Parameters ### Parameters
@ -28,7 +28,7 @@ Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**apiClient** | **apiClient_t \*** | context containing the client configuration | **apiClient** | **apiClient_t \*** | context containing the client configuration |
{{#allParams}} {{#allParams}}
**{{paramName}}** | {{#isPrimitiveType}}{{#isNumber}}**{{{dataType}}}**{{/isNumber}}{{#isLong}}**{{{dataType}}}**{{/isLong}}{{#isInteger}}**{{{dataType}}}**{{/isInteger}}{{#isDouble}}**{{{dataType}}}**{{/isDouble}}{{#isFloat}}**{{{dataType}}}**{{/isFloat}}{{#isBoolean}}**{{dataType}}**{{/isBoolean}}{{#isEnum}}{{#isString}}**{{projectName}}_{{operationId}}_{{baseName}}_e**{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}**{{{dataType}}} \***{{/isString}}{{/isEnum}}{{#isByteArray}}**{{{dataType}}}**{{/isByteArray}}{{#isDate}}**{{{dataType}}}**{{/isDate}}{{#isDateTime}}**{{{dataType}}}**{{/isDateTime}}{{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isFreeFormObject}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{^isEnum}}**[{{{dataType}}}_t]({{{baseType}}}.md) \***{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{/isModel}}{{#isUuid}}**{{dataType}} \***{{/isUuid}}{{#isEmail}}**{{dataType}}**{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isArray}}{{#isMap}}**{{dataType}}**{{/isMap}}{{/isContainer}} | {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} **{{paramName}}** | {{#isPrimitiveType}}{{#isNumber}}**{{{dataType}}}**{{/isNumber}}{{#isLong}}**{{{dataType}}}**{{/isLong}}{{#isInteger}}**{{{dataType}}}**{{/isInteger}}{{#isDouble}}**{{{dataType}}}**{{/isDouble}}{{#isFloat}}**{{{dataType}}}**{{/isFloat}}{{#isBoolean}}**{{dataType}}**{{/isBoolean}}{{#isEnum}}{{#isString}}**{{projectName}}_{{operationId}}_{{baseName}}_e**{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}**{{{dataType}}} \***{{/isString}}{{/isEnum}}{{#isByteArray}}**{{{dataType}}} \***{{/isByteArray}}{{#isDate}}**{{{dataType}}}**{{/isDate}}{{#isDateTime}}**{{{dataType}}}**{{/isDateTime}}{{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isFreeFormObject}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{^isEnum}}**[{{{dataType}}}_t]({{{baseType}}}.md) \***{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{/isModel}}{{#isUuid}}**{{dataType}} \***{{/isUuid}}{{#isEmail}}**{{dataType}}**{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isArray}}{{#isMap}}**{{dataType}}**{{/isMap}}{{/isContainer}} | {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{/allParams}} {{/allParams}}
### Return type ### Return type

View File

@ -164,7 +164,7 @@ char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName
{{/isString}} {{/isString}}
{{/isEnum}} {{/isEnum}}
{{#isByteArray}} {{#isByteArray}}
{{datatype}} {{name}}{{^-last}},{{/-last}} {{datatype}} *{{name}}{{^-last}},{{/-last}}
{{/isByteArray}} {{/isByteArray}}
{{#isBinary}} {{#isBinary}}
{{datatype}} {{name}}{{^-last}},{{/-last}} {{datatype}} {{name}}{{^-last}},{{/-last}}
@ -347,8 +347,8 @@ cJSON *{{classname}}_convertToJSON({{classname}}_t *{{classname}}) {
{{/isString}} {{/isString}}
{{/isEnum}} {{/isEnum}}
{{#isByteArray}} {{#isByteArray}}
if(cJSON_AddNumberToObject(item, "{{{baseName}}}", {{{classname}}}->{{{name}}}) == NULL) { if(cJSON_AddStringToObject(item, "{{{baseName}}}", {{{classname}}}->{{{name}}}) == NULL) {
goto fail; //Byte goto fail; //ByteArray
} }
{{/isByteArray}} {{/isByteArray}}
{{#isBinary}} {{#isBinary}}
@ -481,6 +481,12 @@ cJSON *{{classname}}_convertToJSON({{classname}}_t *{{classname}}) {
goto fail; goto fail;
} }
{{/isString}} {{/isString}}
{{#isByteArray}}
if(cJSON_AddStringToObject(localMapObject, localKeyValue->key, (char*)localKeyValue->value) == NULL)
{
goto fail;
}
{{/isByteArray}}
{{#isNumeric}} {{#isNumeric}}
if(cJSON_AddNumberToObject(localMapObject, localKeyValue->key, *(double *)localKeyValue->value) == NULL) if(cJSON_AddNumberToObject(localMapObject, localKeyValue->key, *(double *)localKeyValue->value) == NULL)
{ {
@ -562,9 +568,9 @@ fail:
{{/isEnum}} {{/isEnum}}
{{#isByteArray}} {{#isByteArray}}
{{^required}}if ({{{name}}}) { {{/required}} {{^required}}if ({{{name}}}) { {{/required}}
if(!cJSON_IsNumber({{{name}}})) if(!cJSON_IsString({{{name}}}))
{ {
goto end; //Byte goto end; //ByteArray
} }
{{/isByteArray}} {{/isByteArray}}
{{#isBinary}} {{#isBinary}}
@ -707,6 +713,13 @@ fail:
} }
localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring)); localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring));
{{/isString}} {{/isString}}
{{#isByteArray}}
if(!cJSON_IsString(localMapObject))
{
goto end;
}
localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring));
{{/isByteArray}}
{{#isBoolean}} {{#isBoolean}}
if(!cJSON_IsBool(localMapObject)) if(!cJSON_IsBool(localMapObject))
{ {
@ -772,7 +785,7 @@ fail:
{{/isString}} {{/isString}}
{{/isEnum}} {{/isEnum}}
{{#isByteArray}} {{#isByteArray}}
{{^required}}{{{name}}} ? {{/required}}{{{name}}}->valueint{{^required}} : 0{{/required}}{{^-last}},{{/-last}} {{^required}}{{{name}}} ? {{/required}}strdup({{{name}}}->valuestring){{^required}} : NULL{{/required}}{{^-last}},{{/-last}}
{{/isByteArray}} {{/isByteArray}}
{{#isBinary}} {{#isBinary}}
{{^required}}{{{name}}} ? {{/required}}decoded_str_{{{name}}}{{^required}} : NULL{{/required}}{{^-last}},{{/-last}} {{^required}}{{{name}}} ? {{/required}}decoded_str_{{{name}}}{{^required}} : NULL{{/required}}{{^-last}},{{/-last}}

View File

@ -114,7 +114,7 @@ typedef struct {{classname}}_t {
{{/isString}} {{/isString}}
{{/isEnum}} {{/isEnum}}
{{#isByteArray}} {{#isByteArray}}
{{datatype}} {{name}}; //Byte {{datatype}} *{{name}}; //ByteArray
{{/isByteArray}} {{/isByteArray}}
{{#isBinary}} {{#isBinary}}
{{datatype}} {{name}}; //binary {{datatype}} {{name}}; //binary
@ -184,7 +184,7 @@ typedef struct {{classname}}_t {
{{/isString}} {{/isString}}
{{/isEnum}} {{/isEnum}}
{{#isByteArray}} {{#isByteArray}}
{{datatype}} {{name}}{{^-last}},{{/-last}} {{datatype}} *{{name}}{{^-last}},{{/-last}}
{{/isByteArray}} {{/isByteArray}}
{{#isBinary}} {{#isBinary}}
{{datatype}} {{name}}{{^-last}},{{/-last}} {{datatype}} {{name}}{{^-last}},{{/-last}}

View File

@ -4,7 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
{{#vars}} {{#vars}}
**{{name}}** | {{^isContainer}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}**{{projectName}}_{{classVarName}}_{{enumName}}_e**{{/isEnum}}{{^isEnum}}[**{{datatype}}_t**]({{complexType}}.md) \*{{/isEnum}}{{/isModel}}{{#isUuid}}**{{datatype}} \***{{/isUuid}}{{#isEmail}}**{{datatype}} \***{{/isEmail}}{{#isFreeFormObject}}[**{{datatype}}_t**]({{complexType}}.md) \*{{/isFreeFormObject}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isNumeric}}**{{datatype}}**{{/isNumeric}}{{#isBoolean}}**{{datatype}}**{{/isBoolean}}{{#isEnum}}{{#isString}}**{{projectName}}_{{classVarName}}_{{enumName}}_e**{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}**{{datatype}} \***{{/isString}}{{/isEnum}}{{#isByteArray}}**{{datatype}}**{{/isByteArray}}{{#isBinary}}**{{datatype}}**{{/isBinary}}{{#isDate}}**{{datatype}} \***{{/isDate}}{{#isDateTime}}**{{datatype}} \***{{/isDateTime}}{{/isPrimitiveType}}{{/isContainer}}{{#isContainer}}{{#isArray}}{{#isPrimitiveType}}**{{datatype}}_t \***{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}_t**]({{complexType}}.md) \*{{/isPrimitiveType}}{{/isArray}}{{#isMap}}**{{datatype}}**{{/isMap}}{{/isContainer}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} **{{name}}** | {{^isContainer}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}**{{projectName}}_{{classVarName}}_{{enumName}}_e**{{/isEnum}}{{^isEnum}}[**{{datatype}}_t**]({{complexType}}.md) \*{{/isEnum}}{{/isModel}}{{#isUuid}}**{{datatype}} \***{{/isUuid}}{{#isEmail}}**{{datatype}} \***{{/isEmail}}{{#isFreeFormObject}}[**{{datatype}}_t**]({{complexType}}.md) \*{{/isFreeFormObject}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isNumeric}}**{{datatype}}**{{/isNumeric}}{{#isBoolean}}**{{datatype}}**{{/isBoolean}}{{#isEnum}}{{#isString}}**{{projectName}}_{{classVarName}}_{{enumName}}_e**{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}**{{datatype}} \***{{/isString}}{{/isEnum}}{{#isByteArray}}**{{datatype}} \***{{/isByteArray}}{{#isBinary}}**{{datatype}}**{{/isBinary}}{{#isDate}}**{{datatype}} \***{{/isDate}}{{#isDateTime}}**{{datatype}} \***{{/isDateTime}}{{/isPrimitiveType}}{{/isContainer}}{{#isContainer}}{{#isArray}}{{#isPrimitiveType}}**{{datatype}}_t \***{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}_t**]({{complexType}}.md) \*{{/isPrimitiveType}}{{/isArray}}{{#isMap}}**{{datatype}}**{{/isMap}}{{/isContainer}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/vars}} {{/vars}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -31,10 +31,16 @@ public interface {{classname}} extends ApiClient.Api {
* @return {{returnType}} * @return {{returnType}}
{{/returnType}} {{/returnType}}
{{#externalDocs}} {{#externalDocs}}
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
@RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{^-last}}&{{/-last}}{{/queryParams}}") @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{^-last}}&{{/-last}}{{/queryParams}}")
@Headers({ @Headers({
{{#vendorExtensions.x-contentType}} "Content-Type: {{vendorExtensions.x-contentType}}", {{#vendorExtensions.x-contentType}} "Content-Type: {{vendorExtensions.x-contentType}}",
@ -72,7 +78,13 @@ public interface {{classname}} extends ApiClient.Api {
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
@RequestLine("{{httpMethod}} {{{path}}}?{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{^-last}}&{{/-last}}{{/queryParams}}") @RequestLine("{{httpMethod}} {{{path}}}?{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{^-last}}&{{/-last}}{{/queryParams}}")
@Headers({ @Headers({
{{#vendorExtensions.x-contentType}} "Content-Type: {{vendorExtensions.x-contentType}}", {{#vendorExtensions.x-contentType}} "Content-Type: {{vendorExtensions.x-contentType}}",

View File

@ -53,9 +53,14 @@ public class {{classname}} {
* @throws IOException if an error occurs while attempting to invoke the API{{#externalDocs}} * @throws IOException if an error occurs while attempting to invoke the API{{#externalDocs}}
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
**/ **/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws IOException { public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws IOException {
{{#returnType}}HttpResponse response = {{/returnType}}{{operationId}}ForHttpResponse({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} {{#returnType}}HttpResponse response = {{/returnType}}{{operationId}}ForHttpResponse({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}}
TypeReference<{{{returnType}}}> typeRef = new TypeReference<{{{returnType}}}>() {}; TypeReference<{{{returnType}}}> typeRef = new TypeReference<{{{returnType}}}>() {};
@ -72,15 +77,23 @@ public class {{classname}} {
* @throws IOException if an error occurs while attempting to invoke the API{{#externalDocs}} * @throws IOException if an error occurs while attempting to invoke the API{{#externalDocs}}
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
**/ **/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#bodyParam}}{{^required}}{{{dataType}}} {{paramName}}, {{/required}}{{/bodyParam}}{{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}Map<String, Object> params) throws IOException { public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#bodyParam}}{{^required}}{{{dataType}}} {{paramName}}, {{/required}}{{/bodyParam}}{{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}Map<String, Object> params) throws IOException {
{{#returnType}}HttpResponse response = {{/returnType}}{{operationId}}ForHttpResponse({{#bodyParam}}{{^required}}{{paramName}}, {{/required}}{{/bodyParam}}{{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}params);{{#returnType}} {{#returnType}}HttpResponse response = {{/returnType}}{{operationId}}ForHttpResponse({{#bodyParam}}{{^required}}{{paramName}}, {{/required}}{{/bodyParam}}{{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}params);{{#returnType}}
TypeReference<{{{returnType}}}> typeRef = new TypeReference<{{{returnType}}}>() {}; TypeReference<{{{returnType}}}> typeRef = new TypeReference<{{{returnType}}}>() {};
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);{{/returnType}} return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);{{/returnType}}
} }
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public HttpResponse {{operationId}}ForHttpResponse({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws IOException { public HttpResponse {{operationId}}ForHttpResponse({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws IOException {
{{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set {{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) { if ({{paramName}} == null) {
@ -112,6 +125,9 @@ public class {{classname}} {
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute(); return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute();
}{{#bodyParam}} }{{#bodyParam}}
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public HttpResponse {{operationId}}ForHttpResponse({{#allParams}}{{#isBodyParam}}java.io.InputStream {{paramName}}{{/isBodyParam}}{{^isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}}{{^-last}}, {{/-last}}{{/allParams}}, String mediaType) throws IOException { public HttpResponse {{operationId}}ForHttpResponse({{#allParams}}{{#isBodyParam}}java.io.InputStream {{paramName}}{{/isBodyParam}}{{^isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}}{{^-last}}, {{/-last}}{{/allParams}}, String mediaType) throws IOException {
{{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set {{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) { if ({{paramName}} == null) {
@ -145,6 +161,9 @@ public class {{classname}} {
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute(); return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute();
}{{/bodyParam}} }{{/bodyParam}}
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public HttpResponse {{operationId}}ForHttpResponse({{#bodyParam}}{{^required}}{{{dataType}}} {{paramName}}, {{/required}}{{/bodyParam}}{{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}Map<String, Object> params) throws IOException { public HttpResponse {{operationId}}ForHttpResponse({{#bodyParam}}{{^required}}{{{dataType}}} {{paramName}}, {{/required}}{{/bodyParam}}{{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#hasRequiredParams}}, {{/hasRequiredParams}}Map<String, Object> params) throws IOException {
{{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set {{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) { if ({{paramName}} == null) {

View File

@ -1,6 +1,8 @@
/** /**
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}{{#isDeprecated}}
*/{{#description}} * @deprecated{{/isDeprecated}}
*/{{#isDeprecated}}
@Deprecated{{/isDeprecated}}{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}} @ApiModel(description = "{{{description}}}"){{/description}}
{{#jackson}} {{#jackson}}
@JsonPropertyOrder({ @JsonPropertyOrder({
@ -187,11 +189,20 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
* maximum: {{maximum}} * maximum: {{maximum}}
{{/maximum}} {{/maximum}}
* @return {{name}} * @return {{name}}
{{#deprecated}}
* @deprecated
{{/deprecated}}
**/ **/
{{#deprecated}}
@Deprecated
{{/deprecated}}
{{#required}} {{#required}}
{{#isNullable}} {{#isNullable}}
@javax.annotation.Nullable @javax.annotation.Nullable
{{/isNullable}} {{/isNullable}}
{{^isNullable}}
@javax.annotation.Nonnull
{{/isNullable}}
{{/required}} {{/required}}
{{^required}} {{^required}}
@javax.annotation.Nullable @javax.annotation.Nullable

View File

@ -44,8 +44,14 @@ public interface {{classname}} {
* {{notes}} * {{notes}}
* *
{{/notes}} {{/notes}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{/summary}} {{/summary}}
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
@{{httpMethod}} @{{httpMethod}}
{{#subresourceOperation}}@Path("{{{path}}}"){{/subresourceOperation}} {{#subresourceOperation}}@Path("{{{path}}}"){{/subresourceOperation}}
{{#hasConsumes}} {{#hasConsumes}}

View File

@ -69,7 +69,13 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{#serializ
* maximum: {{maximum}} * maximum: {{maximum}}
{{/maximum}} {{/maximum}}
* @return {{name}} * @return {{name}}
{{#deprecated}}
* @deprecated
{{/deprecated}}
**/ **/
{{#deprecated}}
@Deprecated
{{/deprecated}}
{{^withXml}} {{^withXml}}
@JsonbProperty("{{baseName}}") @JsonbProperty("{{baseName}}")
{{/withXml}} {{/withXml}}

View File

@ -2,8 +2,10 @@
import {{invokerPackage}}.JSON; import {{invokerPackage}}.JSON;
{{/discriminator}} {{/discriminator}}
/** /**
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}{{#isDeprecated}}
*/{{#description}} * @deprecated{{/isDeprecated}}
*/{{#isDeprecated}}
@Deprecated{{/isDeprecated}}{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}} @ApiModel(description = "{{{description}}}"){{/description}}
{{#jackson}} {{#jackson}}
@JsonPropertyOrder({ @JsonPropertyOrder({
@ -190,11 +192,20 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
* maximum: {{maximum}} * maximum: {{maximum}}
{{/maximum}} {{/maximum}}
* @return {{name}} * @return {{name}}
{{#deprecated}}
* @deprecated
{{/deprecated}}
**/ **/
{{#deprecated}}
@Deprecated
{{/deprecated}}
{{#required}} {{#required}}
{{#isNullable}} {{#isNullable}}
@javax.annotation.Nullable @javax.annotation.Nullable
{{/isNullable}} {{/isNullable}}
{{^isNullable}}
@javax.annotation.Nonnull
{{/isNullable}}
{{/required}} {{/required}}
{{^required}} {{^required}}
@javax.annotation.Nullable @javax.annotation.Nullable

View File

@ -27,6 +27,7 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
{{/withXml}} {{/withXml}}
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -92,6 +93,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null);
private final String separator; private final String separator;
private CollectionFormat(String separator) { private CollectionFormat(String separator) {
this.separator = separator; this.separator = separator;
} }
@ -148,6 +150,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Get the current base path * Get the current base path
*
* @return String the base path * @return String the base path
*/ */
public String getBasePath() { public String getBasePath() {
@ -156,6 +159,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Set the base path, which should include the host * Set the base path, which should include the host
*
* @param basePath the base path * @param basePath the base path
* @return ApiClient this client * @return ApiClient this client
*/ */
@ -166,6 +170,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Get authentications (key: authentication name, value: authentication). * Get authentications (key: authentication name, value: authentication).
*
* @return Map the currently configured authentication types * @return Map the currently configured authentication types
*/ */
public Map<String, Authentication> getAuthentications() { public Map<String, Authentication> getAuthentications() {
@ -182,104 +187,110 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return authentications.get(authName); return authentications.get(authName);
} }
{{#hasHttpBearerMethods}} {{#hasHttpBearerMethods}}
/** /**
* Helper method to set token for HTTP bearer authentication. * Helper method to set token for HTTP bearer authentication.
* @param bearerToken the token *
*/ * @param bearerToken the token
public void setBearerToken(String bearerToken) { */
for (Authentication auth : authentications.values()) { public void setBearerToken(String bearerToken) {
if (auth instanceof HttpBearerAuth) { for (Authentication auth : authentications.values()) {
((HttpBearerAuth) auth).setBearerToken(bearerToken); if (auth instanceof HttpBearerAuth) {
return; ((HttpBearerAuth) auth).setBearerToken(bearerToken);
} return;
}
}
throw new RuntimeException("No Bearer authentication configured!");
} }
throw new RuntimeException("No Bearer authentication configured!");
}
{{/hasHttpBearerMethods}} {{/hasHttpBearerMethods}}
{{#hasHttpBasicMethods}} {{#hasHttpBasicMethods}}
/** /**
* Helper method to set username for the first HTTP basic authentication. * Helper method to set username for the first HTTP basic authentication.
* @param username Username *
*/ * @param username Username
public void setUsername(String username) { */
for (Authentication auth : authentications.values()) { public void setUsername(String username) {
if (auth instanceof HttpBasicAuth) { for (Authentication auth : authentications.values()) {
((HttpBasicAuth) auth).setUsername(username); if (auth instanceof HttpBasicAuth) {
return; ((HttpBasicAuth) auth).setUsername(username);
} return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
} }
throw new RuntimeException("No HTTP basic authentication configured!");
}
/** /**
* Helper method to set password for the first HTTP basic authentication. * Helper method to set password for the first HTTP basic authentication.
* @param password Password * @param password Password
*/ */
public void setPassword(String password) { public void setPassword(String password) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) { if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password); ((HttpBasicAuth) auth).setPassword(password);
return; return;
} }
}
throw new RuntimeException("No HTTP basic authentication configured!");
} }
throw new RuntimeException("No HTTP basic authentication configured!");
}
{{/hasHttpBasicMethods}} {{/hasHttpBasicMethods}}
{{#hasApiKeyMethods}} {{#hasApiKeyMethods}}
/** /**
* Helper method to set API key value for the first API key authentication. * Helper method to set API key value for the first API key authentication.
* @param apiKey the API key *
*/ * @param apiKey the API key
public void setApiKey(String apiKey) { */
for (Authentication auth : authentications.values()) { public void setApiKey(String apiKey) {
if (auth instanceof ApiKeyAuth) { for (Authentication auth : authentications.values()) {
((ApiKeyAuth) auth).setApiKey(apiKey); if (auth instanceof ApiKeyAuth) {
return; ((ApiKeyAuth) auth).setApiKey(apiKey);
} return;
}
}
throw new RuntimeException("No API key authentication configured!");
} }
throw new RuntimeException("No API key authentication configured!");
}
/** /**
* Helper method to set API key prefix for the first API key authentication. * Helper method to set API key prefix for the first API key authentication.
* @param apiKeyPrefix API key prefix *
*/ * @param apiKeyPrefix API key prefix
public void setApiKeyPrefix(String apiKeyPrefix) { */
for (Authentication auth : authentications.values()) { public void setApiKeyPrefix(String apiKeyPrefix) {
if (auth instanceof ApiKeyAuth) { for (Authentication auth : authentications.values()) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); if (auth instanceof ApiKeyAuth) {
return; ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
} return;
}
}
throw new RuntimeException("No API key authentication configured!");
} }
throw new RuntimeException("No API key authentication configured!");
}
{{/hasApiKeyMethods}} {{/hasApiKeyMethods}}
{{#hasOAuthMethods}} {{#hasOAuthMethods}}
/** /**
* Helper method to set access token for the first OAuth2 authentication. * Helper method to set access token for the first OAuth2 authentication.
* @param accessToken Access token *
*/ * @param accessToken Access token
public void setAccessToken(String accessToken) { */
for (Authentication auth : authentications.values()) { public void setAccessToken(String accessToken) {
if (auth instanceof OAuth) { for (Authentication auth : authentications.values()) {
((OAuth) auth).setAccessToken(accessToken); if (auth instanceof OAuth) {
return; ((OAuth) auth).setAccessToken(accessToken);
} return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
} }
throw new RuntimeException("No OAuth2 authentication configured!");
}
{{/hasOAuthMethods}} {{/hasOAuthMethods}}
/** /**
* Set the User-Agent header's value (by adding to the default header map). * Set the User-Agent header's value (by adding to the default header map).
*
* @param userAgent the user agent string * @param userAgent the user agent string
* @return ApiClient this client * @return ApiClient this client
*/ */
@ -291,7 +302,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Add a default header. * Add a default header.
* *
* @param name The header's name * @param name The header's name
* @param value The header's value * @param value The header's value
* @return ApiClient this client * @return ApiClient this client
*/ */
@ -306,7 +317,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Add a default cookie. * Add a default cookie.
* *
* @param name The cookie's name * @param name The cookie's name
* @param value The cookie's value * @param value The cookie's value
* @return ApiClient this client * @return ApiClient this client
*/ */
@ -320,7 +331,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
public void setDebugging(boolean debugging) { public void setDebugging(boolean debugging) {
List<ClientHttpRequestInterceptor> currentInterceptors = this.restTemplate.getInterceptors(); List<ClientHttpRequestInterceptor> currentInterceptors = this.restTemplate.getInterceptors();
if(debugging) { if (debugging) {
if (currentInterceptors == null) { if (currentInterceptors == null) {
currentInterceptors = new ArrayList<ClientHttpRequestInterceptor>(); currentInterceptors = new ArrayList<ClientHttpRequestInterceptor>();
} }
@ -366,9 +377,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
public ApiClient setDateFormat(DateFormat dateFormat) { public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat; this.dateFormat = dateFormat;
{{#threetenbp}} {{#threetenbp}}
for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ for (HttpMessageConverter converter : restTemplate.getMessageConverters()) {
if(converter instanceof AbstractJackson2HttpMessageConverter){ if (converter instanceof AbstractJackson2HttpMessageConverter) {
ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
mapper.setDateFormat(dateFormat); mapper.setDateFormat(dateFormat);
} }
} }
@ -378,6 +389,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Parse the given string into Date object. * Parse the given string into Date object.
*
* @param str the string to parse * @param str the string to parse
* @return the Date parsed from the string * @return the Date parsed from the string
*/ */
@ -391,6 +403,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Format the given Date object into string. * Format the given Date object into string.
*
* @param date the date to format * @param date the date to format
* @return the formatted date as string * @return the formatted date as string
*/ */
@ -400,6 +413,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Format the given parameter object into string. * Format the given parameter object into string.
*
* @param param the object to convert * @param param the object to convert
* @return String the parameter represented as a String * @return String the parameter represented as a String
*/ */
@ -412,8 +426,8 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return formatOffsetDateTime((OffsetDateTime) param); return formatOffsetDateTime((OffsetDateTime) param);
} {{/jsr310}}else if (param instanceof Collection) { } {{/jsr310}}else if (param instanceof Collection) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>) param) { for (Object o : (Collection<?>) param) {
if(b.length() > 0) { if (b.length() > 0) {
b.append(","); b.append(",");
} }
b.append(String.valueOf(o)); b.append(String.valueOf(o));
@ -439,7 +453,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
} }
// collectionFormat is assumed to be "csv" by default // collectionFormat is assumed to be "csv" by default
if(collectionFormat == null) { if (collectionFormat == null) {
collectionFormat = CollectionFormat.CSV; collectionFormat = CollectionFormat.CSV;
} }
@ -448,6 +462,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Converts a parameter to a {@link MultiValueMap} for use in REST requests * Converts a parameter to a {@link MultiValueMap} for use in REST requests
*
* @param collectionFormat The format to convert to * @param collectionFormat The format to convert to
* @param name The name of the parameter * @param name The name of the parameter
* @param value The parameter's value * @param value The parameter's value
@ -460,7 +475,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return params; return params;
} }
if(collectionFormat == null) { if (collectionFormat == null) {
collectionFormat = CollectionFormat.CSV; collectionFormat = CollectionFormat.CSV;
} }
@ -472,7 +487,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return params; return params;
} }
if (valueCollection.isEmpty()){ if (valueCollection.isEmpty()) {
return params; return params;
} }
@ -484,7 +499,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
} }
List<String> values = new ArrayList<String>(); List<String> values = new ArrayList<String>();
for(Object o : valueCollection) { for (Object o : valueCollection) {
values.add(parameterToString(o)); values.add(parameterToString(o));
} }
params.add(name, collectionFormat.collectionToString(values)); params.add(name, collectionFormat.collectionToString(values));
@ -492,8 +507,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return params; return params;
} }
/** /**
* Check if the given {@code String} is a JSON MIME. * Check if the given {@code String} is a JSON MIME.
*
* @param mediaType the input MediaType * @param mediaType the input MediaType
* @return boolean true if the MediaType represents JSON, false otherwise * @return boolean true if the MediaType represents JSON, false otherwise
*/ */
@ -516,6 +532,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
* application/json * application/json
* application/json; charset=UTF8 * application/json; charset=UTF8
* APPLICATION/JSON * APPLICATION/JSON
*
* @param mediaType the input MediaType * @param mediaType the input MediaType
* @return boolean true if the MediaType represents JSON, false otherwise * @return boolean true if the MediaType represents JSON, false otherwise
*/ */
@ -523,8 +540,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$"));
} }
/** /**
* Check if the given {@code String} is a Problem JSON MIME (RFC-7807). * Check if the given {@code String} is a Problem JSON MIME (RFC-7807).
*
* @param mediaType the input MediaType * @param mediaType the input MediaType
* @return boolean true if the MediaType represents Problem JSON, false otherwise * @return boolean true if the MediaType represents Problem JSON, false otherwise
*/ */
@ -576,6 +594,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Select the body to use for the request * Select the body to use for the request
*
* @param obj the body object * @param obj the body object
* @param formParams the form parameters * @param formParams the form parameters
* @param contentType the content type of the request * @param contentType the content type of the request
@ -588,6 +607,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Expand path template with variables * Expand path template with variables
*
* @param pathTemplate path template with placeholders * @param pathTemplate path template with placeholders
* @param variables variables to replace * @param variables variables to replace
* @return path with placeholders replaced by variables * @return path with placeholders replaced by variables
@ -596,12 +616,47 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString();
} }
/**
* Include queryParams in uriParams taking into account the paramName
*
* @param queryParam The query parameters
* @param uriParams The path parameters
* return templatized query string
*/
private String generateQueryUri(MultiValueMap<String, String> queryParams, Map<String, Object> uriParams) {
StringBuilder queryBuilder = new StringBuilder();
queryParams.forEach((name, values) -> {
if (CollectionUtils.isEmpty(values)) {
if (queryBuilder.length() != 0) {
queryBuilder.append('&');
}
queryBuilder.append(name);
} else {
int valueItemCounter = 0;
for (Object value : values) {
if (queryBuilder.length() != 0) {
queryBuilder.append('&');
}
queryBuilder.append(name);
if (value != null) {
String templatizedKey = name + valueItemCounter++;
uriParams.put(templatizedKey, value.toString());
queryBuilder.append('=').append("{").append(templatizedKey).append("}");
}
}
}
});
return queryBuilder.toString();
}
/** /**
* Invoke API by sending HTTP request with the given options. * Invoke API by sending HTTP request with the given options.
* *
* @param <T> the return type to use * @param <T> the return type to use
* @param path The sub-path of the HTTP URL * @param path The sub-path of the HTTP URL
* @param method The request method * @param method The request method
* @param pathParams The path parameters
* @param queryParams The query parameters * @param queryParams The query parameters
* @param body The request body object * @param body The request body object
* @param headerParams The header parameters * @param headerParams The header parameters
@ -613,38 +668,35 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
* @param returnType The return type into which to deserialize the response * @param returnType The return type into which to deserialize the response
* @return ResponseEntity&lt;T&gt; The response of the chosen type * @return ResponseEntity&lt;T&gt; The response of the chosen type
*/ */
public <T> ResponseEntity<T> invokeAPI(String path, HttpMethod method, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException { public <T> ResponseEntity<T> invokeAPI(String path, HttpMethod method, Map<String, Object> pathParams, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); Map<String,Object> uriParams = new HashMap();
if (queryParams != null) { uriParams.putAll(pathParams);
//encode the query parameters in case they contain unsafe characters
for (List<String> values : queryParams.values()) {
if (values != null) {
for (int i = 0; i < values.size(); i++) {
try {
values.set(i, URLEncoder.encode(values.get(i), "utf8"));
} catch (UnsupportedEncodingException e) {
} String finalUri = path;
}
} if (queryParams != null && !queryParams.isEmpty()) {
} //Include queryParams in uriParams taking into account the paramName
builder.queryParams(queryParams); String queryUri = generateQueryUri(queryParams, uriParams);
//Append to finalUri the templatized query string like "?param1={param1Value}&.......
finalUri += "?" + queryUri;
} }
String expandedPath = this.expandPath(finalUri, uriParams);
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(expandedPath);
URI uri; URI uri;
try { try {
uri = new URI(builder.build().toUriString()); uri = new URI(builder.build().toUriString());
} catch(URISyntaxException ex) { } catch (URISyntaxException ex) {
throw new RestClientException("Could not build URL: " + builder.toUriString(), ex); throw new RestClientException("Could not build URL: " + builder.toUriString(), ex);
} }
final BodyBuilder requestBuilder = RequestEntity.method(method, uri); final BodyBuilder requestBuilder = RequestEntity.method(method, uri);
if(accept != null) { if (accept != null) {
requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
} }
if(contentType != null) { if (contentType != null) {
requestBuilder.contentType(contentType); requestBuilder.contentType(contentType);
} }
@ -673,7 +725,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) { protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) {
for (Entry<String, List<String>> entry : headers.entrySet()) { for (Entry<String, List<String>> entry : headers.entrySet()) {
List<String> values = entry.getValue(); List<String> values = entry.getValue();
for(String value : values) { for (String value : values) {
if (value != null) { if (value != null) {
requestBuilder.header(entry.getKey(), value); requestBuilder.header(entry.getKey(), value);
} }
@ -683,7 +735,8 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
/** /**
* Add cookies to the request that is being built * Add cookies to the request that is being built
* @param cookies The cookies to add *
* @param cookies The cookies to add
* @param requestBuilder The current request * @param requestBuilder The current request
*/ */
protected void addCookiesToRequest(MultiValueMap<String, String> cookies, BodyBuilder requestBuilder) { protected void addCookiesToRequest(MultiValueMap<String, String> cookies, BodyBuilder requestBuilder) {
@ -727,9 +780,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
RestTemplate restTemplate = new RestTemplate(messageConverters); RestTemplate restTemplate = new RestTemplate(messageConverters);
{{/withXml}}{{^withXml}}RestTemplate restTemplate = new RestTemplate();{{/withXml}} {{/withXml}}{{^withXml}}RestTemplate restTemplate = new RestTemplate();{{/withXml}}
{{#threetenbp}} {{#threetenbp}}
for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ for (HttpMessageConverter converter : restTemplate.getMessageConverters()) {
if(converter instanceof AbstractJackson2HttpMessageConverter){ if (converter instanceof AbstractJackson2HttpMessageConverter){
ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
ThreeTenModule module = new ThreeTenModule(); ThreeTenModule module = new ThreeTenModule();
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
@ -790,9 +843,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
private String headersToString(HttpHeaders headers) { private String headersToString(HttpHeaders headers) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for(Entry<String, List<String>> entry : headers.entrySet()) { for (Entry<String, List<String>> entry : headers.entrySet()) {
builder.append(entry.getKey()).append("=["); builder.append(entry.getKey()).append("=[");
for(String value : entry.getValue()) { for (String value : entry.getValue()) {
builder.append(value).append(","); builder.append(value).append(",");
} }
builder.setLength(builder.length() - 1); // Get rid of trailing comma builder.setLength(builder.length() - 1); // Get rid of trailing comma
@ -815,3 +868,4 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
} }
} }
} }

View File

@ -67,6 +67,9 @@ public class {{classname}} {
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}} {{#isDeprecated}}
@Deprecated @Deprecated
@ -95,6 +98,9 @@ public class {{classname}} {
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}} {{#isDeprecated}}
@Deprecated @Deprecated
@ -110,7 +116,6 @@ public class {{classname}} {
// create path and map variables // create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();{{#pathParams}} final Map<String, Object> uriVariables = new HashMap<String, Object>();{{#pathParams}}
uriVariables.put("{{baseName}}", {{#collectionFormat}}apiClient.collectionPathParameterToString(ApiClient.CollectionFormat.valueOf("{{{collectionFormat}}}".toUpperCase()), {{{paramName}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}});{{/pathParams}}{{/hasPathParams}} uriVariables.put("{{baseName}}", {{#collectionFormat}}apiClient.collectionPathParameterToString(ApiClient.CollectionFormat.valueOf("{{{collectionFormat}}}".toUpperCase()), {{{paramName}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}});{{/pathParams}}{{/hasPathParams}}
String path = apiClient.expandPath("{{{path}}}", {{#hasPathParams}}uriVariables{{/hasPathParams}}{{^hasPathParams}}Collections.<String, Object>emptyMap(){{/hasPathParams}});
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders(); final HttpHeaders headerParams = new HttpHeaders();
@ -144,7 +149,7 @@ public class {{classname}} {
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} }; String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} };
{{#returnType}}ParameterizedTypeReference<{{{returnType}}}> returnType = new ParameterizedTypeReference<{{{returnType}}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};{{/returnType}} {{#returnType}}ParameterizedTypeReference<{{{returnType}}}> returnType = new ParameterizedTypeReference<{{{returnType}}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};{{/returnType}}
return apiClient.invokeAPI(path, HttpMethod.{{httpMethod}}, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); return apiClient.invokeAPI("{{{path}}}", HttpMethod.{{httpMethod}}, {{#hasPathParams}}uriVariables{{/hasPathParams}}{{^hasPathParams}}Collections.<String, Object>emptyMap(){{/hasPathParams}}, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType);
} }
{{/operation}} {{/operation}}
} }

View File

@ -31,7 +31,13 @@ public interface {{classname}} {
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
{{#formParams}}{{#-first}} {{#formParams}}{{#-first}}
{{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
@{{httpMethod}}("{{{path}}}") @{{httpMethod}}("{{{path}}}")
@ -50,7 +56,13 @@ public interface {{classname}} {
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
{{#formParams}}{{#-first}} {{#formParams}}{{#-first}}
{{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
@{{httpMethod}}("{{{path}}}") @{{httpMethod}}("{{{path}}}")

View File

@ -34,7 +34,13 @@ public interface {{classname}} {
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}} {{/allParams}}
* @return Call&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt; * @return Call&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
{{#formParams}} {{#formParams}}
{{#-first}} {{#-first}}
{{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}} {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}

View File

@ -34,7 +34,13 @@ public interface {{classname}} {
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}} {{/allParams}}
* @return Call&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt; * @return Call&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
{{#formParams}} {{#formParams}}
{{#-first}} {{#-first}}
{{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}} {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}

View File

@ -34,7 +34,13 @@ public interface {{classname}} {
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}} {{/allParams}}
* @return Call&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt; * @return Call&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
{{#formParams}} {{#formParams}}
{{#-first}} {{#-first}}
{{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}} {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}

View File

@ -13,8 +13,14 @@ public interface {{classname}} {
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> handler); void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> handler);
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiClient.AuthInfo authInfo, Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> handler); void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiClient.AuthInfo authInfo, Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> handler);
{{/operation}} {{/operation}}

View File

@ -277,7 +277,7 @@
<dependency> <dependency>
<groupId>com.github.joschi.jackson</groupId> <groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId> <artifactId>jackson-datatype-threetenbp</artifactId>
<version>${jackson-version}</version> <version>2.9.10</version>
</dependency> </dependency>
{{/threetenbp}} {{/threetenbp}}
<dependency> <dependency>

View File

@ -24,6 +24,7 @@ import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.codec.json.Jackson2JsonDecoder; import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder; import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -610,16 +611,60 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
return requestBuilder.retrieve(); return requestBuilder.retrieve();
} }
private WebClient.RequestBodySpec prepareRequest(String path, HttpMethod method, Map<String, Object> pathParams, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames) { /**
* Include queryParams in uriParams taking into account the paramName
* @param queryParam The query parameters
* @param uriParams The path parameters
* return templatized query string
*/
private String generateQueryUri(MultiValueMap<String, String> queryParams, Map<String, Object> uriParams) {
StringBuilder queryBuilder = new StringBuilder();
queryParams.forEach((name, values) -> {
if (CollectionUtils.isEmpty(values)) {
if (queryBuilder.length() != 0) {
queryBuilder.append('&');
}
queryBuilder.append(name);
} else {
int valueItemCounter = 0;
for (Object value : values) {
if (queryBuilder.length() != 0) {
queryBuilder.append('&');
}
queryBuilder.append(name);
if (value != null) {
String templatizedKey = name + valueItemCounter++;
uriParams.put(templatizedKey, value.toString());
queryBuilder.append('=').append("{").append(templatizedKey).append("}");
}
}
}
});
return queryBuilder.toString();
}
private WebClient.RequestBodySpec prepareRequest(String path, HttpMethod method, Map<String, Object> pathParams,
MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams,
MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept,
MediaType contentType, String[] authNames) {
updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
if (queryParams != null) {
builder.queryParams(queryParams); String finalUri = builder.build(false).toUriString();
Map<String, Object> uriParams = new HashMap();
uriParams.putAll(pathParams);
if (queryParams != null && !queryParams.isEmpty()) {
//Include queryParams in uriParams taking into account the paramName
String queryUri = generateQueryUri(queryParams, uriParams);
//Append to finalUri the templatized query string like "?param1={param1Value}&.......
finalUri += "?" + queryUri;
} }
final WebClient.RequestBodySpec requestBuilder = webClient.method(method).uri(builder.build(false).toUriString(), pathParams); final WebClient.RequestBodySpec requestBuilder = webClient.method(method).uri(finalUri, uriParams);
if(accept != null) {
if (accept != null) {
requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
} }
if(contentType != null) { if(contentType != null) {

View File

@ -60,10 +60,16 @@ public class {{classname}} {
{{/allParams}}{{#returnType}} * @return {{returnType}} {{/allParams}}{{#returnType}} * @return {{returnType}}
{{/returnType}} * @throws WebClientResponseException if an error occurs while attempting to invoke the API {{/returnType}} * @throws WebClientResponseException if an error occurs while attempting to invoke the API
{{#externalDocs}} {{#externalDocs}}
* {{description}} * {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a> * @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}} {{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/ */
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
private ResponseSpec {{operationId}}RequestCreation({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection<org.springframework.core.io.AbstractResource>{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException { private ResponseSpec {{operationId}}RequestCreation({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection<org.springframework.core.io.AbstractResource>{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}} {{#allParams}}

View File

@ -12,6 +12,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
{{/fullJavaUtil}} {{/fullJavaUtil}}
/** /**
@ -33,7 +34,7 @@ public class {{classname}}Test {
{{#allParams}} {{#allParams}}
{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection<org.springframework.core.io.AbstractResource>{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}} = null; {{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection<org.springframework.core.io.AbstractResource>{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}} = null;
{{/allParams}} {{/allParams}}
{{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}){{#isArray}}.collectList().block(){{/isArray}}{{^isArray}}.block(){{/isArray}}; {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}){{#isArray}}{{#uniqueItems}}.collect(Collectors.toSet()){{/uniqueItems}}{{^uniqueItems}}.collectList(){{/uniqueItems}}.block(){{/isArray}}{{^isArray}}.block(){{/isArray}};
// TODO: test validations // TODO: test validations
} }

View File

@ -1,6 +1,8 @@
/** /**
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}{{#isDeprecated}}
*/{{#description}} * @deprecated{{/isDeprecated}}
*/{{#isDeprecated}}
@Deprecated{{/isDeprecated}}{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}} @ApiModel(description = "{{{description}}}"){{/description}}
{{#jackson}} {{#jackson}}
@JsonPropertyOrder({ @JsonPropertyOrder({
@ -170,11 +172,20 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
* maximum: {{maximum}} * maximum: {{maximum}}
{{/maximum}} {{/maximum}}
* @return {{name}} * @return {{name}}
{{#deprecated}}
* @deprecated
{{/deprecated}}
**/ **/
{{#deprecated}}
@Deprecated
{{/deprecated}}
{{#required}} {{#required}}
{{#isNullable}} {{#isNullable}}
@javax.annotation.Nullable @javax.annotation.Nullable
{{/isNullable}} {{/isNullable}}
{{^isNullable}}
@javax.annotation.Nonnull
{{/isNullable}}
{{/required}} {{/required}}
{{^required}} {{^required}}
@javax.annotation.Nullable @javax.annotation.Nullable

View File

@ -28,13 +28,23 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* {{{description}}} * {{{description}}}
**/ **/
{{/description}} {{/description}}
{{#isContainer}} {{#vendorExtensions.x-is-jackson-optional-nullable}}
{{#isContainer}}
private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined();
{{/isContainer}}
{{^isContainer}}
private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}};
{{/isContainer}}
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
{{#isContainer}}
private {{{datatypeWithEnum}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}} = null{{/required}}; private {{{datatypeWithEnum}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}} = null{{/required}};
{{/isContainer}} {{/isContainer}}
{{^isContainer}} {{^isContainer}}
private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};
{{/isContainer}} {{/isContainer}}
{{/vars}} {{/vendorExtensions.x-is-jackson-optional-nullable}}
{{/vars}}
{{#vars}} {{#vars}}
/** /**
{{#description}} {{#description}}
@ -51,44 +61,115 @@ import com.fasterxml.jackson.annotation.JsonProperty;
{{/maximum}} {{/maximum}}
* @return {{name}} * @return {{name}}
**/ **/
@JsonProperty("{{baseName}}")
{{#vendorExtensions.x-extra-annotation}} {{#vendorExtensions.x-extra-annotation}}
{{{vendorExtensions.x-extra-annotation}}} {{{vendorExtensions.x-extra-annotation}}}
{{/vendorExtensions.x-extra-annotation}} {{/vendorExtensions.x-extra-annotation}}
{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} {{#isEnum}}{{^isArray}}{{^isMap}}public {{dataType}} {{getter}}() { {{#vendorExtensions.x-is-jackson-optional-nullable}}
{{!unannotated, Jackson would pick this up automatically and add it *in addition* to the _JsonNullable getter field}}
@JsonIgnore
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
@JsonProperty("{{baseName}}")
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} {{#isEnum}}{{^isContainer}}public {{dataType}} {{getter}}() {
{{#vendorExtensions.x-is-jackson-optional-nullable}}
if ({{name}} == null || !{{name}}.isPresent() || {{name}}.get() == null) {
return null;
}
return {{name}}.get().value();
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
if ({{name}} == null) { if ({{name}} == null) {
return null; return null;
} }
return {{name}}.value(); return {{name}}.value();
}{{/isMap}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{#isArray}}public {{{datatypeWithEnum}}} {{getter}}() { {{/vendorExtensions.x-is-jackson-optional-nullable}}
}{{/isContainer}}{{#isContainer}}public {{{datatypeWithEnum}}} {{getter}}() {
{{#vendorExtensions.x-is-jackson-optional-nullable}}
if ({{name}} == null) {
return null;
}
return {{name}}.orElse(null);
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
return {{name}}; return {{name}};
}{{/isArray}}{{/isEnum}}{{#isEnum}}{{#isMap}}public {{{datatypeWithEnum}}} {{getter}}() { {{/vendorExtensions.x-is-jackson-optional-nullable}}
return {{name}}; }{{/isContainer}}{{/isEnum}}{{^isEnum}}public {{{datatypeWithEnum}}} {{getter}}() {
}{{/isMap}}{{/isEnum}}{{^isEnum}}public {{{datatypeWithEnum}}} {{getter}}() { {{#vendorExtensions.x-is-jackson-optional-nullable}}
if ({{name}} == null) {
return null;
}
return {{name}}.orElse(null);
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
return {{name}}; return {{name}};
{{/vendorExtensions.x-is-jackson-optional-nullable}}
}{{/isEnum}} }{{/isEnum}}
{{#vendorExtensions.x-is-jackson-optional-nullable}}
@JsonProperty("{{baseName}}")
public JsonNullable<{{{datatypeWithEnum}}}> {{getter}}_JsonNullable() {
return {{name}};
}
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^isReadOnly}} {{^isReadOnly}}
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
{{#vendorExtensions.x-is-jackson-optional-nullable}}
this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}});
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
this.{{name}} = {{name}};
{{/vendorExtensions.x-is-jackson-optional-nullable}}
}
{{#vendorExtensions.x-is-jackson-optional-nullable}}
@JsonProperty("{{baseName}}")
public void {{setter}}_JsonNullable(JsonNullable<{{{datatypeWithEnum}}}> {{name}}) {
{{! For getters/setters that have name differing from attribute name, we must include setter (albeit private) for jackson to be able to set the attribute}}
this.{{name}} = {{name}}; this.{{name}} = {{name}};
} }
{{/vendorExtensions.x-is-jackson-optional-nullable}}
public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) {
{{#vendorExtensions.x-is-jackson-optional-nullable}}
this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}});
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
this.{{name}} = {{name}}; this.{{name}} = {{name}};
{{/vendorExtensions.x-is-jackson-optional-nullable}}
return this; return this;
} }
{{#isArray}} {{#isArray}}
public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) {
{{#vendorExtensions.x-is-jackson-optional-nullable}}
if (this.{{name}} == null || !this.{{name}}.isPresent()) {
this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}});
}
this.{{name}}.get().add({{name}}Item);
return this;
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
this.{{name}}.add({{name}}Item); this.{{name}}.add({{name}}Item);
return this; return this;
{{/vendorExtensions.x-is-jackson-optional-nullable}}
} }
{{/isArray}} {{/isArray}}
{{#isMap}} {{#isMap}}
public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) {
{{#vendorExtensions.x-is-jackson-optional-nullable}}
if (this.{{name}} == null || !this.{{name}}.isPresent()) {
this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}});
}
this.{{name}}.get().put(key, {{name}}Item);
return this;
{{/vendorExtensions.x-is-jackson-optional-nullable}}
{{^vendorExtensions.x-is-jackson-optional-nullable}}
this.{{name}}.put(key, {{name}}Item); this.{{name}}.put(key, {{name}}Item);
return this; return this;
{{/vendorExtensions.x-is-jackson-optional-nullable}}
} }
{{/isMap}} {{/isMap}}
{{/isReadOnly}} {{/isReadOnly}}

View File

@ -126,6 +126,16 @@ inline FString ToString(const FString& Value)
return Value; return Value;
} }
inline FString ToString(bool Value)
{
return Value ? TEXT("true") : TEXT("false");
}
inline FStringFormatArg ToStringFormatArg(bool Value)
{
return FStringFormatArg(ToString(Value));
}
inline FString ToString(const TArray<uint8>& Value) inline FString ToString(const TArray<uint8>& Value)
{ {
return Base64UrlEncode(Value); return Base64UrlEncode(Value);

View File

@ -73,7 +73,8 @@ class {{classname}} {
extra: <String, dynamic>{ extra: <String, dynamic>{
'secure': <Map<String, String>>[{{^hasAuthMethods}}],{{/hasAuthMethods}}{{#hasAuthMethods}} 'secure': <Map<String, String>>[{{^hasAuthMethods}}],{{/hasAuthMethods}}{{#hasAuthMethods}}
{{#authMethods}}{ {{#authMethods}}{
'type': '{{type}}', 'type': '{{type}}',{{#scheme}}
'scheme': '{{scheme}}',{{/scheme}}
'name': '{{name}}',{{#isApiKey}} 'name': '{{name}}',{{#isApiKey}}
'keyName': '{{keyParamName}}', 'keyName': '{{keyParamName}}',
'where': '{{#isKeyInQuery}}query{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}',{{/isApiKey}} 'where': '{{#isKeyInQuery}}query{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}',{{/isApiKey}}

View File

@ -4,6 +4,7 @@ import 'package:built_value/serializer.dart';
import 'package:{{pubName}}/src/serializers.dart';{{/useBuiltValue}} import 'package:{{pubName}}/src/serializers.dart';{{/useBuiltValue}}
import 'package:{{pubName}}/src/auth/api_key_auth.dart'; import 'package:{{pubName}}/src/auth/api_key_auth.dart';
import 'package:{{pubName}}/src/auth/basic_auth.dart'; import 'package:{{pubName}}/src/auth/basic_auth.dart';
import 'package:{{pubName}}/src/auth/bearer_auth.dart';
import 'package:{{pubName}}/src/auth/oauth.dart'; import 'package:{{pubName}}/src/auth/oauth.dart';
{{#apiInfo}}{{#apis}}import 'package:{{pubName}}/src/api/{{classFilename}}.dart'; {{#apiInfo}}{{#apis}}import 'package:{{pubName}}/src/api/{{classFilename}}.dart';
{{/apis}}{{/apiInfo}} {{/apis}}{{/apiInfo}}
@ -31,6 +32,7 @@ class {{clientName}} {
this.dio.interceptors.addAll([ this.dio.interceptors.addAll([
OAuthInterceptor(), OAuthInterceptor(),
BasicAuthInterceptor(), BasicAuthInterceptor(),
BearerAuthInterceptor(),
ApiKeyAuthInterceptor(), ApiKeyAuthInterceptor(),
]); ]);
} else { } else {
@ -44,6 +46,12 @@ class {{clientName}} {
} }
} }
void setBearerAuth(String name, String token) {
if (this.dio.interceptors.any((i) => i is BearerAuthInterceptor)) {
(this.dio.interceptors.firstWhere((i) => i is BearerAuthInterceptor) as BearerAuthInterceptor).tokens[name] = token;
}
}
void setBasicAuth(String name, String username, String password) { void setBasicAuth(String name, String username, String password) {
if (this.dio.interceptors.any((i) => i is BasicAuthInterceptor)) { if (this.dio.interceptors.any((i) => i is BasicAuthInterceptor)) {
(this.dio.interceptors.firstWhere((i) => i is BasicAuthInterceptor) as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password); (this.dio.interceptors.firstWhere((i) => i is BasicAuthInterceptor) as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password);

View File

@ -8,7 +8,7 @@ class ApiKeyAuthInterceptor extends AuthInterceptor {
@override @override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) { void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
final authInfo = getAuthInfo(options, 'apiKey'); final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'apiKey');
for (final info in authInfo) { for (final info in authInfo) {
final authName = info['name'] as String; final authName = info['name'] as String;
final authKeyName = info['keyName'] as String; final authKeyName = info['keyName'] as String;

View File

@ -5,16 +5,10 @@ abstract class AuthInterceptor extends Interceptor {
/// Get auth information on given route for the given type. /// Get auth information on given route for the given type.
/// Can return an empty list if type is not present on auth data or /// Can return an empty list if type is not present on auth data or
/// if route doesn't need authentication. /// if route doesn't need authentication.
List<Map<String, dynamic>> getAuthInfo(RequestOptions route, String type) { List<Map<String, String>> getAuthInfo(RequestOptions route, bool Function(Map<String, String> secure) handles) {
if (route.extra.containsKey('secure')) { if (route.extra.containsKey('secure')) {
final auth = route.extra['secure'] as List<Map<String, String>>; final auth = route.extra['secure'] as List<Map<String, String>>;
final results = <Map<String, dynamic>>[]; return auth.where((secure) => handles(secure)).toList();
for (final info in auth) {
if (info['type'] == type) {
results.add(info);
}
}
return results;
} }
return []; return [];
} }

View File

@ -19,7 +19,7 @@ class BasicAuthInterceptor extends AuthInterceptor {
RequestOptions options, RequestOptions options,
RequestInterceptorHandler handler, RequestInterceptorHandler handler,
) { ) {
final metadataAuthInfo = getAuthInfo(options, 'basic'); final metadataAuthInfo = getAuthInfo(options, (secure) => (secure['type'] == 'http' && secure['scheme'] == 'basic') || secure['type'] == 'basic');
for (final info in metadataAuthInfo) { for (final info in metadataAuthInfo) {
final authName = info['name'] as String; final authName = info['name'] as String;
final basicAuthInfo = authInfo[authName]; final basicAuthInfo = authInfo[authName];

View File

@ -0,0 +1,23 @@
{{>header}}
import 'package:dio/dio.dart';
import 'package:{{pubName}}/src/auth/auth.dart';
class BearerAuthInterceptor extends AuthInterceptor {
final Map<String, String> tokens = {};
@override
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'http' && secure['scheme'] == 'bearer');
for (final info in authInfo) {
final token = tokens[info['name']];
if (token != null) {
options.headers['Authorization'] = 'Bearer ${token}';
break;
}
}
super.onRequest(options, handler);
}
}

View File

@ -10,7 +10,7 @@ class OAuthInterceptor extends AuthInterceptor {
RequestOptions options, RequestOptions options,
RequestInterceptorHandler handler, RequestInterceptorHandler handler,
) { ) {
final authInfo = getAuthInfo(options, 'oauth'); final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'oauth' && secure['type'] == 'oauth2');
for (final info in authInfo) { for (final info in authInfo) {
final token = tokens[info['name']]; final token = tokens[info['name']];
if (token != null) { if (token != null) {

View File

@ -7,6 +7,8 @@ defmodule {{moduleName}}.Mixfile do
elixir: "~> {{supportedElixirVersion}}", elixir: "~> {{supportedElixirVersion}}",
build_embedded: Mix.env == :prod, build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod, start_permanent: Mix.env == :prod,
package: package(),
description: "{{appDescription}}",
deps: deps()] deps: deps()]
end end
@ -34,4 +36,12 @@ defmodule {{moduleName}}.Mixfile do
{{/deps}} {{/deps}}
] ]
end end
defp package() do
[
name: "{{#underscored}}{{packageName}}{{/underscored}}",
files: ~w(lib mix.exs README* LICENSE*),
licenses: ["{{licenseId}}"]
]
end
end end

View File

@ -29,10 +29,12 @@
-spec init(Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) -> -spec init(Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) ->
{cowboy_rest, Req :: cowboy_req:req(), State :: state()}. {cowboy_rest, Req :: cowboy_req:req(), State :: state()}.
init(Req, {Operations, LogicHandler, ValidatorState}) -> init(Req, {Operations, LogicHandler, ValidatorMod}) ->
Method = cowboy_req:method(Req), Method = cowboy_req:method(Req),
OperationID = maps:get(Method, Operations, undefined), OperationID = maps:get(Method, Operations, undefined),
ValidatorState = ValidatorMod:get_validator_state(),
error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), error_logger:info_msg("Attempt to process operation: ~p", [OperationID]),
State = #state{ State = #state{

View File

@ -1,6 +1,6 @@
-module({{packageName}}_router). -module({{packageName}}_router).
-export([get_paths/1]). -export([get_paths/1, get_validator_state/0]).
-type operations() :: #{ -type operations() :: #{
Method :: binary() => {{packageName}}_api:operation_id() Method :: binary() => {{packageName}}_api:operation_id()
@ -9,7 +9,7 @@
-type init_opts() :: { -type init_opts() :: {
Operations :: operations(), Operations :: operations(),
LogicHandler :: atom(), LogicHandler :: atom(),
ValidatorState :: jesse_state:state() ValidatorMod :: module()
}. }.
-export_type([init_opts/0]). -export_type([init_opts/0]).
@ -62,9 +62,15 @@ get_operations() ->
}{{^-last}},{{/-last}}{{/operation}}{{^-last}},{{/-last}}{{/operations}}{{/apis}}{{/apiInfo}} }{{^-last}},{{/-last}}{{/operation}}{{^-last}},{{/-last}}{{/operations}}{{/apis}}{{/apiInfo}}
}. }.
get_validator_state() ->
persistent_term:get({?MODULE, validator_state}).
prepare_validator() -> prepare_validator() ->
R = jsx:decode(element(2, file:read_file(get_openapi_path()))), R = jsx:decode(element(2, file:read_file(get_openapi_path()))),
jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]). JesseState = jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]),
persistent_term:put({?MODULE, validator_state}, JesseState),
?MODULE.
get_openapi_path() -> get_openapi_path() ->

View File

@ -27,6 +27,8 @@ module {{title}}.API
, {{title}}ClientError(..) , {{title}}ClientError(..)
-- ** Servant -- ** Servant
, {{title}}API , {{title}}API
-- ** Plain WAI Application
, serverWaiApplication{{title}}
) where ) where
import {{title}}.Types import {{title}}.Types
@ -232,7 +234,13 @@ run{{title}}MiddlewareServer Config{..} middleware backend = do
let warpSettings = Warp.defaultSettings let warpSettings = Warp.defaultSettings
& Warp.setPort (baseUrlPort url) & Warp.setPort (baseUrlPort url)
& Warp.setHost (fromString $ baseUrlHost url) & Warp.setHost (fromString $ baseUrlHost url)
liftIO $ Warp.runSettings warpSettings $ middleware $ serve (Proxy :: Proxy {{title}}API) (serverFromBackend backend) liftIO $ Warp.runSettings warpSettings $ middleware $ serverWaiApplication{{title}} backend
-- | Plain "Network.Wai" Application for the {{title}} server.
--
-- Can be used to implement e.g. tests that call the API without a full webserver.
serverWaiApplication{{title}} :: {{title}}Backend (ExceptT ServerError IO) -> Application
serverWaiApplication{{title}} backend = serve (Proxy :: Proxy {{title}}API) (serverFromBackend backend)
where where
serverFromBackend {{title}}Backend{..} = serverFromBackend {{title}}Backend{..} =
({{#apis}}{{#operations}}{{#operation}}coerce {{operationId}}{{^-last}} :<|> ({{#apis}}{{#operations}}{{#operation}}coerce {{operationId}}{{^-last}} :<|>

View File

@ -16,7 +16,7 @@
<cucumber-java.version>1.2.5</cucumber-java.version> <cucumber-java.version>1.2.5</cucumber-java.version>
<cucumber-reporting.version>3.10.0</cucumber-reporting.version> <cucumber-reporting.version>3.10.0</cucumber-reporting.version>
<javax-annotation-version>1.3.2</javax-annotation-version> <javax-annotation-version>1.3.2</javax-annotation-version>
<springfox-swagger2>2.6.1-SNAPSHOT</springfox-swagger2> <springfox-swagger2>2.6.0</springfox-swagger2>
<springfox-swagger-ui>2.6.0</springfox-swagger-ui> <springfox-swagger-ui>2.6.0</springfox-swagger-ui>
<slf4j-api>1.7.25</slf4j-api> <slf4j-api>1.7.25</slf4j-api>
<logstash-logback-encoder>4.11</logstash-logback-encoder> <logstash-logback-encoder>4.11</logstash-logback-encoder>
@ -36,14 +36,6 @@
<!-- lookup parent from repository --> <!-- lookup parent from repository -->
</parent> </parent>
<repositories> <repositories>
<repository>
<id>oss-snapshots</id>
<name>JFrog OSS Snapshots</name>
<url>https://oss.jfrog.org/simple/oss-snapshot-local/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository> <repository>
<id>central</id> <id>central</id>
<name>Maven Repository Switchboard</name> <name>Maven Repository Switchboard</name>

View File

@ -53,13 +53,20 @@ test {
dependencies { dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
{{^doNotUseRxAndCoroutines}}
{{#useCoroutines}}
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1"
{{/useCoroutines}}
{{/doNotUseRxAndCoroutines}}
{{#moshi}} {{#moshi}}
{{^moshiCodeGen}} {{^moshiCodeGen}}
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
implementation "com.squareup.moshi:moshi-kotlin:1.12.0" implementation "com.squareup.moshi:moshi-kotlin:1.12.0"
implementation "com.squareup.moshi:moshi-adapters:1.12.0"
{{/moshiCodeGen}} {{/moshiCodeGen}}
{{#moshiCodeGen}} {{#moshiCodeGen}}
implementation "com.squareup.moshi:moshi:1.12.0" implementation "com.squareup.moshi:moshi:1.12.0"
implementation "com.squareup.moshi:moshi-adapters:1.12.0"
kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0" kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0"
{{/moshiCodeGen}} {{/moshiCodeGen}}
{{/moshi}} {{/moshi}}
@ -121,4 +128,4 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi" freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi"
} }
} }
{{/kotlinx_serialization}} {{/kotlinx_serialization}}

View File

@ -4,6 +4,12 @@ package {{apiPackage}}
{{#imports}}import {{import}} {{#imports}}import {{import}}
{{/imports}} {{/imports}}
{{^doNotUseRxAndCoroutines}}
{{#useCoroutines}}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
{{/useCoroutines}}
{{/doNotUseRxAndCoroutines}}
import {{packageName}}.infrastructure.ApiClient import {{packageName}}.infrastructure.ApiClient
import {{packageName}}.infrastructure.ClientException import {{packageName}}.infrastructure.ClientException
import {{packageName}}.infrastructure.ClientError import {{packageName}}.infrastructure.ClientError
@ -40,7 +46,7 @@ import {{packageName}}.infrastructure.toMultiValue
{{#isDeprecated}} {{#isDeprecated}}
@Deprecated(message = "This operation is deprecated.") @Deprecated(message = "This operation is deprecated.")
{{/isDeprecated}} {{/isDeprecated}}
{{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} { {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{^doNotUseRxAndCoroutines}}{{#useCoroutines}} = withContext(Dispatchers.IO){{/useCoroutines}}{{/doNotUseRxAndCoroutines}} {
{{#isDeprecated}} {{#isDeprecated}}
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
{{/isDeprecated}} {{/isDeprecated}}
@ -50,7 +56,7 @@ import {{packageName}}.infrastructure.toMultiValue
localVariableConfig localVariableConfig
) )
return when (localVarResponse.responseType) { return{{^doNotUseRxAndCoroutines}}{{#useCoroutines}}@withContext{{/useCoroutines}}{{/doNotUseRxAndCoroutines}} when (localVarResponse.responseType) {
ResponseType.Success -> {{#returnType}}(localVarResponse as Success<*>).data as {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} ResponseType.Success -> {{#returnType}}(localVarResponse as Success<*>).data as {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")

View File

@ -55,6 +55,15 @@ import org.threeten.bp.LocalTime
import org.threeten.bp.OffsetDateTime import org.threeten.bp.OffsetDateTime
import org.threeten.bp.OffsetTime import org.threeten.bp.OffsetTime
{{/threetenbp}} {{/threetenbp}}
{{#gson}}
import com.google.gson.reflect.TypeToken
{{/gson}}
{{#jackson}}
import com.fasterxml.jackson.core.type.TypeReference
{{/jackson}}
{{#moshi}}
import com.squareup.moshi.adapter
{{/moshi}}
{{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient(val baseUrl: String) { {{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient(val baseUrl: String) {
{{#nonPublicApi}}internal {{/nonPublicApi}}companion object { {{#nonPublicApi}}internal {{/nonPublicApi}}companion object {
@ -173,6 +182,9 @@ import org.threeten.bp.OffsetTime
else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.") else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.")
} }
{{#moshi}}
@OptIn(ExperimentalStdlibApi::class)
{{/moshi}}
protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? {
if(body == null) { if(body == null) {
return null return null
@ -201,7 +213,7 @@ import org.threeten.bp.OffsetTime
return f as T return f as T
} }
return when(mediaType) { return when(mediaType) {
JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).fromJson(bodyContent){{/moshi}}{{#gson}}Serializer.gson.fromJson(bodyContent, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, T::class.java){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.decodeFromString<T>(bodyContent){{/kotlinx_serialization}} JsonMediaType -> {{#moshi}}Serializer.moshi.adapter<T>().fromJson(bodyContent){{/moshi}}{{#gson}}Serializer.gson.fromJson(bodyContent, (object: TypeToken<T>(){}).getType()){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, object: TypeReference<T>() {}){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.decodeFromString<T>(bodyContent){{/kotlinx_serialization}}
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
} }
} }

View File

@ -1,4 +1,4 @@
{{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} {{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}}
@ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}}{{#deprecated}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}}{{#deprecated}}
@Deprecated(message = ""){{/deprecated}} @Deprecated(message = ""){{/deprecated}}
@field:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{nameInCamelCase}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{#defaultValue}}{{defaultValue}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}} @field:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{nameInCamelCase}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}

View File

@ -1,3 +1,3 @@
{{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} {{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}}
@ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}}
@field:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{nameInCamelCase}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isReadOnly}}?{{/isReadOnly}}{{#defaultValue}} = {{defaultValue}}{{/defaultValue}}{{#isReadOnly}}{{^defaultValue}} = null{{/defaultValue}}{{/isReadOnly}} @field:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{nameInCamelCase}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isReadOnly}}?{{/isReadOnly}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#isReadOnly}}{{^defaultValue}} = null{{/defaultValue}}{{/isReadOnly}}

View File

@ -3,7 +3,6 @@ language: php
# https://docs.travis-ci.com/user/reference/bionic/#php-support # https://docs.travis-ci.com/user/reference/bionic/#php-support
dist: bionic dist: bionic
php: php:
- 7.2
- 7.3 - 7.3
- 7.4 - 7.4
before_install: "composer install" before_install: "composer install"

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* ApiException * ApiException
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* Configuration * Configuration
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}
@ -20,7 +20,7 @@ namespace {{invokerPackage}};
/** /**
* Configuration Class Doc Comment * Configuration Class Doc Comment
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* ApiException * ApiException
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -2,7 +2,7 @@
/** /**
* ModelInterface * ModelInterface
* *
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{modelPackage}} * @package {{modelPackage}}

View File

@ -2,7 +2,7 @@
/** /**
* ObjectSerializer * ObjectSerializer
* *
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -12,7 +12,8 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}).
### Requirements ### Requirements
PHP 7.2 and later. PHP 7.3 and later.
Should also work with PHP 8.0 but has not been tested.
### Composer ### Composer

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* {{classname}} * {{classname}}
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* {{classname}}Test * {{classname}}Test
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -1,5 +1,7 @@
{ {
"name": "{{gitUserId}}/{{gitRepoId}}", {{#composerPackageName}}
"name": "{{composerPackageName}}",
{{/composerPackageName}}
{{#artifactVersion}} {{#artifactVersion}}
"version": "{{artifactVersion}}", "version": "{{artifactVersion}}",
{{/artifactVersion}} {{/artifactVersion}}
@ -22,7 +24,7 @@
} }
], ],
"require": { "require": {
"php": ">=7.2", "php": "^7.3 || ^8.0",
"ext-curl": "*", "ext-curl": "*",
"ext-json": "*", "ext-json": "*",
"ext-mbstring": "*", "ext-mbstring": "*",

View File

@ -4,7 +4,7 @@
/** /**
* {{classname}} * {{classname}}
* *
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -4,7 +4,7 @@
/** /**
* {{classname}}Test * {{classname}}Test
* *
* PHP version 7.2 * PHP version 7.3
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}

View File

@ -4,6 +4,9 @@ rvm:
- 2.3 - 2.3
- 2.4 - 2.4
- 2.5 - 2.5
- 2.6
- 2.7
- 3.0
script: script:
- bundle install --path vendor/bundle - bundle install --path vendor/bundle
- bundle exec rspec - bundle exec rspec

View File

@ -251,6 +251,12 @@ extension {{projectName}} {
{{#queryParams}} {{#queryParams}}
var {{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}} var {{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}
{{/queryParams}} {{/queryParams}}
enum CodingKeys: String, CodingKey {
{{#queryParams}}
case {{paramName}}{{#baseName}} = "{{baseName}}"{{/baseName}}
{{/queryParams}}
}
} }
try localVariableRequest.query.encode(QueryParams({{#queryParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/queryParams}})){{/hasQueryParams}} try localVariableRequest.query.encode(QueryParams({{#queryParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/queryParams}})){{/hasQueryParams}}
{{#hasBodyParam}} {{#hasBodyParam}}

View File

@ -277,7 +277,7 @@ private var managerStore = SynchronizedDictionary<String, Alamofire.SessionManag
let filenameKey = "filename=" let filenameKey = "filename="
guard let range = contentItem.range(of: filenameKey) else { guard let range = contentItem.range(of: filenameKey) else {
break continue
} }
filename = contentItem filename = contentItem

View File

@ -270,7 +270,7 @@ private var urlSessionStore = SynchronizedDictionary<String, URLSession>()
let filenameKey = "filename=" let filenameKey = "filename="
guard let range = contentItem.range(of: filenameKey) else { guard let range = contentItem.range(of: filenameKey) else {
break continue
} }
filename = contentItem filename = contentItem

View File

@ -0,0 +1,89 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen;
import com.google.common.collect.Sets;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.QueryParameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.parser.core.models.ParseOptions;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.languages.AbstractCSharpCodegen;
import org.openapitools.codegen.languages.AspNetCoreServerCodegen;
import org.openapitools.codegen.languages.CSharpNetCoreClientCodegen;
import org.openapitools.codegen.templating.mustache.CamelCaseLambda;
import org.openapitools.codegen.templating.mustache.IndentedLambda;
import org.openapitools.codegen.templating.mustache.LowercaseLambda;
import org.openapitools.codegen.templating.mustache.TitlecaseLambda;
import org.openapitools.codegen.templating.mustache.UppercaseLambda;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.SemVer;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.accessibility.AccessibleAttributeSequence;
import static org.testng.Assert.*;
public class CSharpOperationTest {
@Test
public void assertMethodOptionalParameterDataType() {
assertEquals(getOperationOptionalParameterDataType(new AspNetCoreServerCodegen(), 2, false), "System.IO.Stream");
assertEquals(getOperationOptionalParameterDataType(new AspNetCoreServerCodegen(), 2, true), "System.IO.Stream?");
assertEquals(getOperationOptionalParameterDataType(new AspNetCoreServerCodegen(), 3, false), "System.IO.Stream");
assertEquals(getOperationOptionalParameterDataType(new AspNetCoreServerCodegen(), 3, true), "System.IO.Stream?");
assertEquals(getOperationOptionalParameterDataType(new CSharpNetCoreClientCodegen(), 2, false), "System.IO.Stream");
assertEquals(getOperationOptionalParameterDataType(new CSharpNetCoreClientCodegen(), 2, true), "System.IO.Stream?");
assertEquals(getOperationOptionalParameterDataType(new CSharpNetCoreClientCodegen(), 3, false), "System.IO.Stream");
assertEquals(getOperationOptionalParameterDataType(new CSharpNetCoreClientCodegen(), 3, true), "System.IO.Stream?");
}
public String getOperationOptionalParameterDataType(final AbstractCSharpCodegen codegen, final int openApiVersion, final Boolean nullableReferenceTypes){
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/" + Integer.toString(openApiVersion) + "_0/petstore-with-fake-endpoints-models-for-testing.yaml");
codegen.setNullableReferenceTypes(nullableReferenceTypes);
codegen.setOpenAPI(openAPI);
final String path = "/pet/{petId}/uploadImage";
final Operation postOperation = openAPI.getPaths().get(path).getPost();
final CodegenOperation codegenOperation = codegen.fromOperation(path, "post", postOperation, null);
return codegenOperation.allParams.get(2).dataType;
}
}

View File

@ -22,10 +22,8 @@ import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.*; import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses; import io.swagger.v3.oas.models.responses.ApiResponses;
import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.*;
import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.languages.AbstractJavaCodegen;
import org.openapitools.codegen.CodegenResponse;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.JavaCXFClientCodegen; import org.openapitools.codegen.languages.JavaCXFClientCodegen;
import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.BeanValidationFeatures;
import org.openapitools.codegen.languages.features.GzipTestFeatures; import org.openapitools.codegen.languages.features.GzipTestFeatures;
@ -179,4 +177,121 @@ public class JavaCXFClientCodegenTest {
Assert.assertTrue(codegen.isUseGzipFeatureForTests()); Assert.assertTrue(codegen.isUseGzipFeatureForTests());
} }
@Test
public void testOpenApiNullableAdditionalProperty() throws Exception {
JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
codegen.processOpts();
Assert.assertNotNull(codegen.additionalProperties().get(AbstractJavaCodegen.OPENAPI_NULLABLE));
Assert.assertTrue(codegen.isOpenApiNullable());
codegen.additionalProperties().put(AbstractJavaCodegen.OPENAPI_NULLABLE, false);
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get(AbstractJavaCodegen.OPENAPI_NULLABLE), Boolean.FALSE);
Assert.assertFalse(codegen.isOpenApiNullable());
}
@Test
public void testPostProcessNullableModelPropertyWithOpenApiNullableEnabled() throws Exception {
JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
codegen.additionalProperties().put(AbstractJavaCodegen.JACKSON, true);
codegen.additionalProperties().put(AbstractJavaCodegen.OPENAPI_NULLABLE, true);
codegen.processOpts();
CodegenModel codegenModel = new CodegenModel();
CodegenProperty codegenProperty = new CodegenProperty();
codegenProperty.required = false;
codegenProperty.isNullable = true;
codegen.postProcessModelProperty(codegenModel, codegenProperty);
Assert.assertTrue(codegenModel.imports.contains("JsonNullable"));
Assert.assertTrue(codegenModel.imports.contains("JsonIgnore"));
Assert.assertEquals(codegenProperty.getVendorExtensions().get("x-is-jackson-optional-nullable"), Boolean.TRUE);
}
@Test
public void testPostProcessNullableModelPropertyWithOpenApiNullableDisabled() throws Exception {
JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
codegen.additionalProperties().put(AbstractJavaCodegen.JACKSON, true);
codegen.additionalProperties().put(AbstractJavaCodegen.OPENAPI_NULLABLE, false);
codegen.processOpts();
CodegenModel codegenModel = new CodegenModel();
CodegenProperty codegenProperty = new CodegenProperty();
codegenProperty.required = false;
codegenProperty.isNullable = true;
codegen.postProcessModelProperty(codegenModel, codegenProperty);
Assert.assertFalse(codegenModel.imports.contains("JsonNullable"));
Assert.assertFalse(codegenModel.imports.contains("JsonIgnore"));
Assert.assertNull(codegenProperty.getVendorExtensions().get("x-is-jackson-optional-nullable"));
}
@Test
public void testPostProcessNullableModelPropertyWithOpenApiNullableEnabledForRequiredProperties() throws Exception {
JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
codegen.additionalProperties().put(AbstractJavaCodegen.JACKSON, true);
codegen.additionalProperties().put(AbstractJavaCodegen.OPENAPI_NULLABLE, true);
codegen.processOpts();
CodegenModel codegenModel = new CodegenModel();
CodegenProperty codegenProperty = new CodegenProperty();
codegenProperty.required = true;
codegenProperty.isNullable = true;
codegen.postProcessModelProperty(codegenModel, codegenProperty);
Assert.assertFalse(codegenModel.imports.contains("JsonNullable"));
Assert.assertFalse(codegenModel.imports.contains("JsonIgnore"));
Assert.assertNull(codegenProperty.getVendorExtensions().get("x-is-jackson-optional-nullable"));
}
@Test
public void testPostProcessNotNullableModelPropertyWithOpenApiNullableEnabled() throws Exception {
JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
codegen.additionalProperties().put(AbstractJavaCodegen.JACKSON, true);
codegen.additionalProperties().put(AbstractJavaCodegen.OPENAPI_NULLABLE, true);
codegen.processOpts();
CodegenModel codegenModel = new CodegenModel();
CodegenProperty codegenProperty = new CodegenProperty();
codegenProperty.required = false;
codegenProperty.isNullable = false;
codegen.postProcessModelProperty(codegenModel, codegenProperty);
Assert.assertFalse(codegenModel.imports.contains("JsonNullable"));
Assert.assertFalse(codegenModel.imports.contains("JsonIgnore"));
Assert.assertNull(codegenProperty.getVendorExtensions().get("x-is-jackson-optional-nullable"));
}
@Test
public void testPostProcessNullableModelPropertyWithOpenApiNullableEnabledButJacksonDisabled() throws Exception {
JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
codegen.additionalProperties().put(AbstractJavaCodegen.JACKSON, false);
codegen.additionalProperties().put(AbstractJavaCodegen.OPENAPI_NULLABLE, true);
codegen.processOpts();
CodegenModel codegenModel = new CodegenModel();
CodegenProperty codegenProperty = new CodegenProperty();
codegenProperty.required = false;
codegenProperty.isNullable = true;
codegen.postProcessModelProperty(codegenModel, codegenProperty);
Assert.assertFalse(codegenModel.imports.contains("JsonNullable"));
Assert.assertFalse(codegenModel.imports.contains("JsonIgnore"));
Assert.assertNull(codegenProperty.getVendorExtensions().get("x-is-jackson-optional-nullable"));
}
@Test
public void testUseJackson() throws Exception {
JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
codegen.processOpts();
Assert.assertNull(codegen.additionalProperties().get(AbstractJavaCodegen.JACKSON));
Assert.assertFalse(codegen.isUseJackson());
codegen.additionalProperties().put(AbstractJavaCodegen.JACKSON, true);
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get(AbstractJavaCodegen.JACKSON), Boolean.TRUE);
Assert.assertTrue(codegen.isUseJackson());
}
} }

View File

@ -23,6 +23,7 @@ import java.nio.file.Paths;
import static org.openapitools.codegen.TestUtils.assertFileContains; import static org.openapitools.codegen.TestUtils.assertFileContains;
import static org.openapitools.codegen.TestUtils.assertFileNotContains; import static org.openapitools.codegen.TestUtils.assertFileNotContains;
import static org.openapitools.codegen.languages.AbstractJavaCodegen.JACKSON;
public abstract class JavaJaxrsBaseTest { public abstract class JavaJaxrsBaseTest {
@ -59,7 +60,7 @@ public abstract class JavaJaxrsBaseTest {
@Test @Test
public void doNotGenerateJsonAnnotationForPolymorphismIfJsonExclude() throws IOException { public void doNotGenerateJsonAnnotationForPolymorphismIfJsonExclude() throws IOException {
codegen.additionalProperties().put("jackson", false); codegen.additionalProperties().put(JACKSON, false);
File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit(); output.deleteOnExit();
String outputPath = output.getAbsolutePath().replace('\\', '/'); String outputPath = output.getAbsolutePath().replace('\\', '/');

View File

@ -22,6 +22,7 @@ import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenType; import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.languages.AbstractPhpCodegen; import org.openapitools.codegen.languages.AbstractPhpCodegen;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.util.Arrays; import java.util.Arrays;
@ -100,6 +101,27 @@ public class AbstractPhpCodegenTest {
Assert.assertEquals(codegenOperation.produces.get(1).get("mediaType"), "application/json"); Assert.assertEquals(codegenOperation.produces.get(1).get("mediaType"), "application/json");
} }
@Test(dataProvider = "composerNames", description = "Issue #9998")
public void testGetComposerPackageName(String gitUserId, String gitRepoId, String result) {
final AbstractPhpCodegen codegen = new P_AbstractPhpCodegen();
codegen.processOpts();
codegen.setGitUserId(gitUserId);
codegen.setGitRepoId(gitRepoId);
Assert.assertEquals(codegen.getComposerPackageName(), result);
}
@DataProvider(name = "composerNames")
public static Object[][] composerNames() {
return new Object[][] {
{"", "", ""},
{"null", "null", ""},
{"GIT_REPO_ID", "GIT_USER_ID", ""},
{"git_repo_id", "git_user_id", "git_repo_id/git_user_id"},
{"foo", "bar", "foo/bar"},
};
}
private static class P_AbstractPhpCodegen extends AbstractPhpCodegen { private static class P_AbstractPhpCodegen extends AbstractPhpCodegen {
@Override @Override
public CodegenType getTag() { public CodegenType getTag() {

View File

@ -2121,3 +2121,24 @@ components:
default: '2010-01-01T10:10:10.000111+01:00' default: '2010-01-01T10:10:10.000111+01:00'
example: '2010-01-01T10:10:10.000111+01:00' example: '2010-01-01T10:10:10.000111+01:00'
format: date-time format: date-time
DeprecatedObject:
type: object
deprecated: true
properties:
name:
type: string
ObjectWithDeprecatedFields:
type: object
properties:
uuid:
type: string
id:
type: number
deprecated: true
deprecatedRef:
$ref: '#/components/schemas/DeprecatedObject'
bars:
type: array
deprecated: true
items:
$ref: '#/components/schemas/Bar'

View File

@ -1861,4 +1861,25 @@ components:
- value - value
properties: properties:
value: value:
$ref: '#/components/schemas/OuterEnumInteger' $ref: '#/components/schemas/OuterEnumInteger'
DeprecatedObject:
type: object
deprecated: true
properties:
name:
type: string
ObjectWithDeprecatedFields:
type: object
properties:
uuid:
type: string
id:
type: number
deprecated: true
deprecatedRef:
$ref: '#/components/schemas/DeprecatedObject'
bars:
type: array
deprecated: true
items:
$ref: '#/components/schemas/Bar'

View File

@ -1779,6 +1779,12 @@ components:
enum: enum:
- 1.1 - 1.1
- -1.2 - -1.2
enum_bool:
type: boolean
enum:
- false
boolEnum:
$ref: '#/components/schemas/BooleanEnum'
stringEnum: stringEnum:
$ref: '#/components/schemas/StringEnum' $ref: '#/components/schemas/StringEnum'
IntegerEnum: IntegerEnum:
@ -2444,4 +2450,8 @@ components:
hearing: hearing:
type: boolean type: boolean
seeingGhosts: seeingGhosts:
type: boolean type: boolean
BooleanEnum:
type: boolean
enum:
- true

View File

@ -1 +1 @@
5.1.1-SNAPSHOT 5.2.1-SNAPSHOT

View File

@ -36,6 +36,30 @@ inline FString ToString(const OpenAPIOrder::StatusEnum& Value)
return TEXT(""); return TEXT("");
} }
FString OpenAPIOrder::EnumToString(const OpenAPIOrder::StatusEnum& EnumValue)
{
return ToString(EnumValue);
}
inline bool FromString(const FString& EnumAsString, OpenAPIOrder::StatusEnum& Value)
{
static TMap<FString, OpenAPIOrder::StatusEnum> StringToEnum = {
{ TEXT("placed"), OpenAPIOrder::StatusEnum::Placed },
{ TEXT("approved"), OpenAPIOrder::StatusEnum::Approved },
{ TEXT("delivered"), OpenAPIOrder::StatusEnum::Delivered }, };
const auto Found = StringToEnum.Find(EnumAsString);
if(Found)
Value = *Found;
return Found != nullptr;
}
bool OpenAPIOrder::EnumFromString(const FString& EnumAsString, OpenAPIOrder::StatusEnum& EnumValue)
{
return FromString(EnumAsString, EnumValue);
}
inline FStringFormatArg ToStringFormatArg(const OpenAPIOrder::StatusEnum& Value) inline FStringFormatArg ToStringFormatArg(const OpenAPIOrder::StatusEnum& Value)
{ {
return FStringFormatArg(ToString(Value)); return FStringFormatArg(ToString(Value));
@ -51,17 +75,8 @@ inline bool TryGetJsonValue(const TSharedPtr<FJsonValue>& JsonValue, OpenAPIOrde
FString TmpValue; FString TmpValue;
if (JsonValue->TryGetString(TmpValue)) if (JsonValue->TryGetString(TmpValue))
{ {
static TMap<FString, OpenAPIOrder::StatusEnum> StringToEnum = { if(FromString(TmpValue, Value))
{ TEXT("placed"), OpenAPIOrder::StatusEnum::Placed },
{ TEXT("approved"), OpenAPIOrder::StatusEnum::Approved },
{ TEXT("delivered"), OpenAPIOrder::StatusEnum::Delivered }, };
const auto Found = StringToEnum.Find(TmpValue);
if(Found)
{
Value = *Found;
return true; return true;
}
} }
return false; return false;
} }

View File

@ -36,6 +36,30 @@ inline FString ToString(const OpenAPIPet::StatusEnum& Value)
return TEXT(""); return TEXT("");
} }
FString OpenAPIPet::EnumToString(const OpenAPIPet::StatusEnum& EnumValue)
{
return ToString(EnumValue);
}
inline bool FromString(const FString& EnumAsString, OpenAPIPet::StatusEnum& Value)
{
static TMap<FString, OpenAPIPet::StatusEnum> StringToEnum = {
{ TEXT("available"), OpenAPIPet::StatusEnum::Available },
{ TEXT("pending"), OpenAPIPet::StatusEnum::Pending },
{ TEXT("sold"), OpenAPIPet::StatusEnum::Sold }, };
const auto Found = StringToEnum.Find(EnumAsString);
if(Found)
Value = *Found;
return Found != nullptr;
}
bool OpenAPIPet::EnumFromString(const FString& EnumAsString, OpenAPIPet::StatusEnum& EnumValue)
{
return FromString(EnumAsString, EnumValue);
}
inline FStringFormatArg ToStringFormatArg(const OpenAPIPet::StatusEnum& Value) inline FStringFormatArg ToStringFormatArg(const OpenAPIPet::StatusEnum& Value)
{ {
return FStringFormatArg(ToString(Value)); return FStringFormatArg(ToString(Value));
@ -51,17 +75,8 @@ inline bool TryGetJsonValue(const TSharedPtr<FJsonValue>& JsonValue, OpenAPIPet:
FString TmpValue; FString TmpValue;
if (JsonValue->TryGetString(TmpValue)) if (JsonValue->TryGetString(TmpValue))
{ {
static TMap<FString, OpenAPIPet::StatusEnum> StringToEnum = { if(FromString(TmpValue, Value))
{ TEXT("available"), OpenAPIPet::StatusEnum::Available },
{ TEXT("pending"), OpenAPIPet::StatusEnum::Pending },
{ TEXT("sold"), OpenAPIPet::StatusEnum::Sold }, };
const auto Found = StringToEnum.Find(TmpValue);
if(Found)
{
Value = *Found;
return true; return true;
}
} }
return false; return false;
} }

View File

@ -132,10 +132,10 @@ void OpenAPIPetApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceede
InOutResponse.SetHttpResponseCode(EHttpResponseCodes::RequestTimeout); InOutResponse.SetHttpResponseCode(EHttpResponseCodes::RequestTimeout);
} }
bool OpenAPIPetApi::AddPet(const AddPetRequest& Request, const FAddPetDelegate& Delegate /*= FAddPetDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::AddPet(const AddPetRequest& Request, const FAddPetDelegate& Delegate /*= FAddPetDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -148,7 +148,8 @@ bool OpenAPIPetApi::AddPet(const AddPetRequest& Request, const FAddPetDelegate&
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate) const void OpenAPIPetApi::OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate) const
@ -158,10 +159,10 @@ void OpenAPIPetApi::OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponseP
Delegate.ExecuteIfBound(Response); Delegate.ExecuteIfBound(Response);
} }
bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetDelegate& Delegate /*= FDeletePetDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetDelegate& Delegate /*= FDeletePetDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -174,7 +175,8 @@ bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetD
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate) const void OpenAPIPetApi::OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate) const
@ -184,10 +186,10 @@ void OpenAPIPetApi::OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpRespon
Delegate.ExecuteIfBound(Response); Delegate.ExecuteIfBound(Response);
} }
bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, const FFindPetsByStatusDelegate& Delegate /*= FFindPetsByStatusDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, const FFindPetsByStatusDelegate& Delegate /*= FFindPetsByStatusDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -200,7 +202,8 @@ bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, con
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate) const void OpenAPIPetApi::OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate) const
@ -210,10 +213,10 @@ void OpenAPIPetApi::OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHtt
Delegate.ExecuteIfBound(Response); Delegate.ExecuteIfBound(Response);
} }
bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const FFindPetsByTagsDelegate& Delegate /*= FFindPetsByTagsDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const FFindPetsByTagsDelegate& Delegate /*= FFindPetsByTagsDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -226,7 +229,8 @@ bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const F
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate) const void OpenAPIPetApi::OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate) const
@ -236,10 +240,10 @@ void OpenAPIPetApi::OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpR
Delegate.ExecuteIfBound(Response); Delegate.ExecuteIfBound(Response);
} }
bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetByIdDelegate& Delegate /*= FGetPetByIdDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetByIdDelegate& Delegate /*= FGetPetByIdDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -252,7 +256,8 @@ bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetBy
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate) const void OpenAPIPetApi::OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate) const
@ -262,10 +267,10 @@ void OpenAPIPetApi::OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpRespo
Delegate.ExecuteIfBound(Response); Delegate.ExecuteIfBound(Response);
} }
bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetDelegate& Delegate /*= FUpdatePetDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetDelegate& Delegate /*= FUpdatePetDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -278,7 +283,8 @@ bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetD
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate) const void OpenAPIPetApi::OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate) const
@ -288,10 +294,10 @@ void OpenAPIPetApi::OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpRespon
Delegate.ExecuteIfBound(Response); Delegate.ExecuteIfBound(Response);
} }
bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, const FUpdatePetWithFormDelegate& Delegate /*= FUpdatePetWithFormDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, const FUpdatePetWithFormDelegate& Delegate /*= FUpdatePetWithFormDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -304,7 +310,8 @@ bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, c
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate) const void OpenAPIPetApi::OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate) const
@ -314,10 +321,10 @@ void OpenAPIPetApi::OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHt
Delegate.ExecuteIfBound(Response); Delegate.ExecuteIfBound(Response);
} }
bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFileDelegate& Delegate /*= FUploadFileDelegate()*/) const FHttpRequestPtr OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFileDelegate& Delegate /*= FUploadFileDelegate()*/) const
{ {
if (!IsValid()) if (!IsValid())
return false; return nullptr;
FHttpRequestRef HttpRequest = CreateHttpRequest(Request); FHttpRequestRef HttpRequest = CreateHttpRequest(Request);
HttpRequest->SetURL(*(Url + Request.ComputePath())); HttpRequest->SetURL(*(Url + Request.ComputePath()));
@ -330,7 +337,8 @@ bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFi
Request.SetupHttpRequest(HttpRequest); Request.SetupHttpRequest(HttpRequest);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate);
return HttpRequest->ProcessRequest(); HttpRequest->ProcessRequest();
return HttpRequest;
} }
void OpenAPIPetApi::OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate) const void OpenAPIPetApi::OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate) const

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