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

This commit is contained in:
William Cheng 2021-10-19 12:55:59 +08:00
commit 730636ad31
656 changed files with 13585 additions and 21040 deletions

56
.github/workflows/gradle-test.yaml vendored Normal file
View File

@ -0,0 +1,56 @@
name: Gradle tests (Java samples)
on:
push:
branches:
- master
- '[5-9]+.[0-9]+.x'
- "java*"
paths:
- 'samples/client/petstore/java/**'
pull_request:
branches:
- master
- '[5-9]+.[0-9]+.x'
paths:
- 'samples/openapi3/client/petstore/java/**'
env:
GRADLE_VERSION: 7.2
jobs:
build:
name: Gradle tests
runs-on: ubuntu-latest
container: gradle:jdk8
strategy:
fail-fast: true
matrix:
sample:
- samples/client/petstore/java/jersey2-java8-localdatetime
- samples/client/petstore/java/jersey2-java8
- samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8
- samples/openapi3/client/petstore/java/jersey2-java8-special-characters
- samples/openapi3/client/petstore/java/jersey2-java8
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
with:
distribution: 'adopt'
java-version: 8
# Cache Gradle Dependencies
- name: Setup Gradle Dependencies Cache
uses: actions/cache@v2
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/*.gradle', '**/*.gradle.kts') }}
# Cache Gradle Wrapper
- name: Setup Gradle Wrapper Cache
uses: actions/cache@v2
with:
path: ~/.gradle/wrapper
key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}
- name: Build
working-directory: ${{ matrix.sample }}
run: /bin/sh gradlew build -x test

View File

@ -1,2 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.3/apache-maven-3.8.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@ -828,7 +828,10 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2021-07-29 - [How To Rewrite a Huge Codebase](https://dzone.com/articles/how-to-rewrite-a-huge-code-base) by [Curtis Poe](https://dzone.com/users/4565446/publiusovidius.html)
- 2021-08-21 - [Generating Client APIs using Swagger Part 1](https://medium.com/@flowsquad/generating-client-apis-using-swagger-part-1-2d46f13f5e92) by [FlowSquad.io](https://medium.com/@flowsquad)
- 2021-09-11 - [Invoking AWS ParallelCluster API](https://docs.aws.amazon.com/parallelcluster/latest/ug/api-reference-v3.html) at [AWS ParallelCluster API official documentation](https://docs.aws.amazon.com/parallelcluster/latest/ug/api-reference-v3.html)
- 2021-09-20 - [OpenAPI Generator - The Babel Fish of the API World](https://www.youtube.com/watch?v=s2zMtwd5klg) by [Cliffano Subagio (Principal Engineer at Shine Solutions)](https://github.com/cliffano) at [Apidays LIVE Australia 2021](https://www.apidays.global/australia2021/)
- 2021-10-02 - [How to Write Fewer Lines of Code with the OpenAPI Generator](https://hackernoon.com/how-to-write-fewer-lines-of-code-with-the-openapi-generator) by [Mikhail Alfa](https://hackernoon.com/u/alphamikle)
- 2021-10-12 - [OpenAPI Generator : 4000 étoiles sur GitHub et des spaghettis](https://www.youtube.com/watch?v=9hEsNBSqTFk) by [Jérémie Bresson](https://github.com/jmini) at [Devoxx FR 2021](https://cfp.devoxx.fr/2021/speaker/jeremie_bresson)
- 2021-10-17 - [Generate a TypeScript HTTP Client From An OpenAPI Spec In DotNET 5](https://richardwillis.info/blog/generate-a-type-script-http-client-from-an-open-api-spec-in-dot-net-5) by [Richard Willis](https://github.com/badsyntax)
## [6 - About Us](#table-of-contents)

View File

@ -1,10 +0,0 @@
generatorName: dart
outputDir: samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/dart2
typeMappings:
Client: "ModelClient"
File: "ModelFile"
additionalProperties:
hideGenerationTimestamp: "true"
serializationLibrary: json_serializable

View File

@ -10,3 +10,4 @@ additionalProperties:
dateLibrary: java8
useOneOfDiscriminatorLookup: true
disallowAdditionalPropertiesIfNotPresent: false
gradleProperties: "\n# JVM arguments\norg.gradle.jvmargs=-Xmx2024m -XX:MaxPermSize=512m\n# set timeout\norg.gradle.daemon.idletimeout=3600000\n# show all warnings\norg.gradle.warning.mode=all"

View File

@ -0,0 +1,8 @@
generatorName: kotlin
outputDir: samples/client/petstore/kotlin-enum-default-value
inputSpec: modules/openapi-generator/src/test/resources/3_0/kotlin/issue10591-enum-defaultValue.yaml
templateDir: modules/openapi-generator/src/main/resources/kotlin-client
additionalProperties:
artifactId: kotlin-enum-default-value
serializableModel: "true"
dateLibrary: java8

View File

@ -1,10 +0,0 @@
generatorName: spring
outputDir: samples/client/petstore/spring-cloud-no-nullable
library: spring-cloud
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
artifactId: petstore-spring-cloud-no-nullable
responseWrapper: HystrixCommand
hideGenerationTimestamp: "true"
openApiNullable: "false"

View File

@ -1,9 +1,8 @@
generatorName: spring
outputDir: samples/client/petstore/spring-cloud
library: spring-cloud
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/JavaSpring
additionalProperties:
artifactId: petstore-spring-cloud
responseWrapper: HystrixCommand
hideGenerationTimestamp: "true"

View File

@ -19,7 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|pubLibrary|Library name in generated code| |null|
|pubName|Name in generated pubspec| |null|
|pubVersion|Version in generated pubspec| |null|
|serializationLibrary|Specify serialization library|<dl><dt>**native_serialization**</dt><dd>Use native serializer, backwards compatible</dd><dt>**json_serializable**</dt><dd>Use json_serializable. Experimental and subject to breaking changes without further notice</dd></dl>|native_serialization|
|serializationLibrary|Specify serialization library|<dl><dt>**native_serialization**</dt><dd>Use native serializer, backwards compatible</dd></dl>|native_serialization|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|Source folder for generated code| |null|

View File

@ -30,6 +30,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|dynamicOperations|Generate operations dynamically at runtime from an OAS| |false|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|gradleProperties|Append additional Gradle proeprties to the gradle.properties file| |null|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|

View File

@ -52,7 +52,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|performBeanValidation|Use Bean Validation Impl. to perform BeanValidation| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|reactive|wrap responses in Mono/Flux Reactor types (spring-boot only)| |false|
|responseWrapper|wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, HystrixCommand, RxObservable, RxSingle or fully qualified type)| |null|
|responseWrapper|wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, RxObservable, RxSingle or fully qualified type)| |null|
|returnSuccessCode|Generated server returns 2xx code| |false|
|scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git|
|scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git|

View File

@ -2,7 +2,7 @@
id: integrations
title: Workflow Integrations
---
## Workflow Integration (Maven, GitHub, CI/CD)
## Workflow Integration (Gradle, Maven, GitHub, CI/CD)
### Gradle Integration

View File

@ -1,341 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Based on configuration from Google https://github.com/google/styleguide/blob/gh-pages/eclipse-java-google-style.xml
With adjustments for our project - see comments -->
<profiles version="13">
<profile kind="CodeFormatterProfile" name="GoogleStyle" version="13">
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_prefer_two_fragments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_comment_inline_tags" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_local_variable_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter" value="1040"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression.count_dependent" value="16|4|80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration.count_dependent" value="16|4|49"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments" value="16"/>
<setting id="org.eclipse.jdt.core.compiler.source" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_local_variable_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants.count_dependent" value="16|5|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="100"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="16"/>
<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_type_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_field_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.comment_new_line_at_start_of_html_paragraph" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comment_prefix" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_parameter_annotation" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
<!-- We use 4 spaces to separate, not 2 -->
<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter.count_dependent" value="1040|-1|1040"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.force_if_else_statement_brace" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="3"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_package_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type" value="1585"/>
<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_new_anonymous_class" value="20"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="100"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="true"/>
<!-- Leave block comments alone -->
<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_member_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_for_statement" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
</profile>
</profiles>

View File

@ -36,6 +36,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
@ -79,14 +80,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<configuration>
<!-- Point at the eclipse-formatter.xml in the parent project directory -->
<configFile>${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml</configFile>
</configuration>
</plugin>
</plugins>
</build>
@ -152,13 +145,13 @@
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<!-- <version>${testng-version}</version> -->
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-version}</version>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -32,16 +32,17 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava-version}</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -70,9 +71,4 @@
</build>
</profile>
</profiles>
<properties>
<slf4j-version>1.7.29</slf4j-version>
<guava-version>26.0-jre</guava-version>
</properties>
</project>

View File

@ -16,8 +16,6 @@
package org.openapitools.codegen.config;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -48,13 +46,13 @@ public final class GeneratorSettings implements Serializable {
private String artifactVersion;
private String library;
private final ImmutableMap<String, String> instantiationTypes;
private final ImmutableMap<String, String> typeMappings;
private final ImmutableMap<String, Object> additionalProperties;
private final ImmutableMap<String, String> importMappings;
private final ImmutableSet<String> languageSpecificPrimitives;
private final ImmutableMap<String, String> reservedWordMappings;
private final ImmutableMap<String, String> serverVariables;
private final Map<String, String> instantiationTypes;
private final Map<String, String> typeMappings;
private final Map<String, Object> additionalProperties;
private final Map<String, String> importMappings;
private final Set<String> languageSpecificPrimitives;
private final Map<String, String> reservedWordMappings;
private final Map<String, String> serverVariables;
private String gitHost;
private String gitUserId;
@ -348,12 +346,12 @@ public final class GeneratorSettings implements Serializable {
artifactId = builder.artifactId;
artifactVersion = builder.artifactVersion;
library = builder.library;
instantiationTypes = ImmutableMap.copyOf(builder.instantiationTypes);
typeMappings = ImmutableMap.copyOf(builder.typeMappings);
importMappings = ImmutableMap.copyOf(builder.importMappings);
languageSpecificPrimitives = ImmutableSet.copyOf(builder.languageSpecificPrimitives);
reservedWordMappings = ImmutableMap.copyOf(builder.reservedWordMappings);
serverVariables = ImmutableMap.copyOf(builder.serverVariables);
instantiationTypes = Collections.unmodifiableMap(builder.instantiationTypes);
typeMappings = Collections.unmodifiableMap(builder.typeMappings);
importMappings = Collections.unmodifiableMap(builder.importMappings);
languageSpecificPrimitives = Collections.unmodifiableSet(builder.languageSpecificPrimitives);
reservedWordMappings = Collections.unmodifiableMap(builder.reservedWordMappings);
serverVariables = Collections.unmodifiableMap(builder.serverVariables);
gitHost = builder.gitHost;
gitUserId = builder.gitUserId;
gitRepoId = builder.gitRepoId;
@ -408,7 +406,7 @@ public final class GeneratorSettings implements Serializable {
additional.put("httpUserAgent", httpUserAgent);
}
additionalProperties = ImmutableMap.copyOf(additional);
additionalProperties = Collections.unmodifiableMap(additional);
}
/**
@ -417,13 +415,13 @@ public final class GeneratorSettings implements Serializable {
@SuppressWarnings("unused")
public GeneratorSettings() {
setDefaults();
instantiationTypes = ImmutableMap.of();
typeMappings = ImmutableMap.of();
additionalProperties = ImmutableMap.of();
importMappings = ImmutableMap.of();
languageSpecificPrimitives = ImmutableSet.of();
reservedWordMappings = ImmutableMap.of();
serverVariables = ImmutableMap.of();
instantiationTypes = Collections.unmodifiableMap(new HashMap<>(0));
typeMappings = Collections.unmodifiableMap(new HashMap<>(0));
additionalProperties = Collections.unmodifiableMap(new HashMap<>(0));
importMappings = Collections.unmodifiableMap(new HashMap<>(0));
languageSpecificPrimitives = Collections.unmodifiableSet(new HashSet<>(0));
reservedWordMappings = Collections.unmodifiableMap(new HashMap<>(0));
serverVariables = Collections.unmodifiableMap(new HashMap<>(0));
}
private void setDefaults() {

View File

@ -16,7 +16,6 @@
package org.openapitools.codegen.config;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -25,10 +24,7 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ -51,7 +47,7 @@ public class WorkflowSettings {
public static final boolean DEFAULT_STRICT_SPEC_BEHAVIOR = true;
public static final boolean DEFAULT_GENERATE_ALIAS_AS_MODEL = false;
public static final String DEFAULT_TEMPLATING_ENGINE_NAME = "mustache";
public static final ImmutableMap<String, String> DEFAULT_GLOBAL_PROPERTIES = ImmutableMap.of();
public static final Map<String, String> DEFAULT_GLOBAL_PROPERTIES = Collections.unmodifiableMap(new HashMap<>());
private String inputSpec;
private String outputDir = DEFAULT_OUTPUT_DIR;
@ -68,7 +64,7 @@ public class WorkflowSettings {
private String templateDir;
private String templatingEngineName = DEFAULT_TEMPLATING_ENGINE_NAME;
private String ignoreFileOverride;
private ImmutableMap<String, ?> globalProperties = DEFAULT_GLOBAL_PROPERTIES;
private Map<String, ?> globalProperties = DEFAULT_GLOBAL_PROPERTIES;
private WorkflowSettings(Builder builder) {
this.inputSpec = builder.inputSpec;
@ -84,7 +80,7 @@ public class WorkflowSettings {
this.templateDir = builder.templateDir;
this.templatingEngineName = builder.templatingEngineName;
this.ignoreFileOverride = builder.ignoreFileOverride;
this.globalProperties = ImmutableMap.copyOf(builder.globalProperties);
this.globalProperties = Collections.unmodifiableMap(builder.globalProperties);
this.generateAliasAsModel = builder.generateAliasAsModel;
}

View File

@ -16,7 +16,6 @@
package org.openapitools.codegen.meta;
import com.google.common.collect.ImmutableList;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.meta.features.annotations.AnnotationType;
@ -203,7 +202,7 @@ public class FeatureSet {
}
public List<AnnotationType> getSource() {
return ImmutableList.copyOf(source);
return Collections.unmodifiableList(source);
}
}

View File

@ -106,7 +106,7 @@
<dependency>
<groupId>org.gradle</groupId>
<artifactId>gradle-tooling-api</artifactId>
<version>${gradleVersion}</version>
<version>5.6.4</version>
</dependency>
</dependencies>
</plugin>

View File

@ -17,7 +17,6 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<sonar.exclusions>**/src/main/java/org/openapitools/codegen/plugin/**/*</sonar.exclusions>
<!-- used for integration tests verification scripts, managed by the test harness plugin -->
<groovy.version>3.0.5</groovy.version>
</properties>
<dependencies>
<dependency>
@ -59,7 +58,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<!-- <version>4.12</version> -->
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -117,14 +116,6 @@
<configLocation>${project.parent.basedir}${file.separator}google_checkstyle.xml</configLocation>
</configuration>
</plugin>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<configuration>
<!-- Point at the eclipse-formatter.xml in the parent project directory -->
<configFile>${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml</configFile>
</configuration>
</plugin>
</plugins>
</build>
<profiles>

View File

@ -12,13 +12,8 @@
<packaging>jar</packaging>
<name>openapi-generator-online</name>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<spring-boot-version>2.2.9.RELEASE</spring-boot-version>
<spring-boot.version>2.5.5</spring-boot.version>
<springfox-version>3.0.0</springfox-version>
<junit-version>4.13</junit-version>
<jackson-version>2.10.2</jackson-version>
<sonar.exclusions>**/org/openapitools/codegen/online/**/*</sonar.exclusions>
</properties>
<dependencyManagement>
@ -26,7 +21,7 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot-version}</version>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -54,7 +49,7 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-version}</version>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
@ -120,16 +115,6 @@
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- Bean Validation API support -->
<dependency>
<groupId>jakarta.validation</groupId>
@ -141,6 +126,12 @@
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -151,12 +142,5 @@
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -28,7 +28,6 @@ public class GenApiControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void clientLanguages() throws Exception {
getLanguages("clients", "java");

View File

@ -27,17 +27,17 @@
<extension>
<groupId>org.jvnet.wagon-svn</groupId>
<artifactId>wagon-svn</artifactId>
<version>1.12</version>
<version>${wagon-svn.version}</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh-external</artifactId>
<version>2.10</version>
<version>${wagon-ssh-external.version}</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-webdav</artifactId>
<version>1.0-beta-2</version>
<version>${wagon-webdav.version}</version>
</extension>
</extensions>
<directory>target</directory>
@ -107,16 +107,16 @@
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.source}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifestEntries>
@ -138,20 +138,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
<version>${maven-site-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
</plugin>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<configuration>
<!-- Point at the eclipse-formatter.xml in the parent project directory -->
<configFile>${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml</configFile>
</configuration>
<version>${maven-release-plugin.version}</version>
</plugin>
</plugins>
</build>
@ -222,7 +214,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.1</version>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<debug>true</debug>
<links>
@ -243,7 +235,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
<version>${maven-project-info-reports-plugin.version}</version>
<reportSets>
<reportSet>
<reports>
@ -254,85 +246,71 @@
</plugin>
</plugins>
</reporting>
<properties>
<diffutils-version>1.3.0</diffutils-version>
<guava-version>26.0-jre</guava-version>
<generex-version>1.0.2</generex-version>
<rxgen-version>1.3</rxgen-version>
<jackson-version>2.10.1</jackson-version>
<jackson-threetenbp-version>2.10.0</jackson-threetenbp-version>
<kotlin-version>1.3.60</kotlin-version>
</properties>
<dependencies>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
<version>${swagger-core.version}</version>
</dependency>
<dependency>
<groupId>${swagger-parser-groupid}</groupId>
<groupId>${swagger-parser-groupid.version}</groupId>
<artifactId>swagger-parser</artifactId>
<version>${swagger-parser-version}</version>
<version>${swagger-parser.version}</version>
</dependency>
<dependency>
<groupId>com.samskivert</groupId>
<artifactId>jmustache</artifactId>
<version>${jmustache-version}</version>
<version>${jmustache.version}</version>
</dependency>
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars</artifactId>
<version>${handlebars.java-version}</version>
<version>${handlebars-java.version}</version>
</dependency>
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>${handlebars.java-version}</version>
<version>${handlebars-java.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io-version}</version>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-ext</artifactId>
<version>${slf4j-version}</version>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j-version}</version>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang-version}</version>
<version>${commons-lang.version}</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>${commons-cli-version}</version>
<version>${commons-cli.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava-version}</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.tngtech.archunit</groupId>
@ -349,7 +327,7 @@
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<!-- <version>${testng-version}</version> -->
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -361,13 +339,13 @@
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections-version}</version>
<version>${reflections.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.java-diff-utils</groupId>
<artifactId>diffutils</artifactId>
<version>${diffutils-version}</version>
<version>${diffutils.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -378,33 +356,28 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-version}</version>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.mifmif</groupId>
<artifactId>generex</artifactId>
<version>${generex-version}</version>
<version>${generex.version}</version>
</dependency>
<dependency>
<groupId>com.github.curious-odd-man</groupId>
<artifactId>rgxgen</artifactId>
<version>${rxgen-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
<version>${rxgen.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>${jackson-threetenbp-version}</version>
<version>${jackson-threetenbp.version}</version>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
@ -414,19 +387,19 @@
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin-version}</version>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-compiler-embeddable</artifactId>
<version>${kotlin-version}</version>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-script-util</artifactId>
<version>${kotlin-version}</version>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -87,6 +87,15 @@ public class CodegenOperation {
return nonempty(queryParams);
}
/**
* Check if there's at least one query parameter or passing API keys in query
*
* @return true if query parameter exists or passing API keys in query, false otherwise
*/
public boolean getHasQueryParamsOrAuth() {
return getHasQueryParams() || (authMethods != null && authMethods.stream().anyMatch(authMethod -> authMethod.isKeyInQuery));
}
/**
* Check if there's at least one header parameter
*

View File

@ -168,7 +168,7 @@ public class DefaultCodegen implements CodegenConfig {
protected Map<String, String> reservedWordsMappings = new HashMap<String, String>();
protected String templateDir;
protected String embeddedTemplateDir;
protected Map<String, Object> additionalProperties = new HashMap<String, Object>();
protected Map<String, Object> additionalProperties = new HashMap<>();
protected Map<String, String> serverVariables = new HashMap<String, String>();
protected Map<String, Object> vendorExtensions = new HashMap<String, Object>();
/*
@ -387,7 +387,7 @@ public class DefaultCodegen implements CodegenConfig {
* If common lambdas are not desired, override addMustacheLambdas() method
* and return empty builder.
*
* @return preinitialized map builder with common lambdas
* @return preinitialized map with common lambdas
*/
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
@ -3419,7 +3419,7 @@ public class DefaultCodegen implements CodegenConfig {
property.example = toExampleValue(p);
} catch (Exception e) {
LOGGER.error("Error in generating `example` for the property {}. Default to ERROR_TO_EXAMPLE_VALUE. Enable debugging for more info.", property.baseName);
LOGGER.debug("Exception from toExampleValue: {}", e);
LOGGER.debug("Exception from toExampleValue: {}", e.getMessage());
property.example = "ERROR_TO_EXAMPLE_VALUE";
}
property.defaultValue = toDefaultValue(p);
@ -3574,13 +3574,13 @@ public class DefaultCodegen implements CodegenConfig {
;
}
Boolean isAnyTypeWithNothingElseSet = (ModelUtils.isAnyType(p) &&
boolean isAnyTypeWithNothingElseSet = (ModelUtils.isAnyType(p) &&
(p.getProperties() == null || p.getProperties().isEmpty()) &&
!ModelUtils.isComposedSchema(p) &&
p.getAdditionalProperties() == null && p.getNot() == null && p.getEnum() == null);
if (!ModelUtils.isArraySchema(p) && !ModelUtils.isMapSchema(p) && !isFreeFormObject(p) && !isAnyTypeWithNothingElseSet) {
/** schemas that are not Array, not ModelUtils.isMapSchema, not isFreeFormObject, not AnyType with nothing else set
/* schemas that are not Array, not ModelUtils.isMapSchema, not isFreeFormObject, not AnyType with nothing else set
* so primitve schemas int, str, number, referenced schemas, AnyType schemas with properties, enums, or composition
*/
String type = getSchemaType(p);
@ -3673,7 +3673,7 @@ public class DefaultCodegen implements CodegenConfig {
protected Boolean isPropertyInnerMostEnum(CodegenProperty property) {
CodegenProperty currentProperty = getMostInnerItems(property);
return currentProperty == null ? false : currentProperty.isEnum;
return currentProperty != null && currentProperty.isEnum;
}
protected CodegenProperty getMostInnerItems(CodegenProperty property) {

View File

@ -17,7 +17,6 @@
package org.openapitools.codegen;
import com.google.common.collect.ImmutableList;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
@ -112,7 +111,7 @@ public class DefaultGenerator implements Generator {
this.config = opts.getConfig();
List<TemplateDefinition> userFiles = opts.getUserDefinedTemplates();
if (userFiles != null) {
this.userDefinedTemplates = ImmutableList.copyOf(userFiles);
this.userDefinedTemplates = Collections.unmodifiableList(userFiles);
}
TemplateManagerOptions templateManagerOptions = new TemplateManagerOptions(this.config.isEnableMinimalUpdate(),this.config.isSkipOverwrite());

View File

@ -1,12 +1,12 @@
package org.openapitools.codegen;
import com.google.common.collect.ImmutableMap;
import org.openapitools.codegen.api.TemplateProcessor;
import org.openapitools.codegen.templating.TemplateManagerOptions;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@ -32,7 +32,7 @@ public class DryRunTemplateManager implements TemplateProcessor {
* @return An immutable copy of the dry run status.
*/
public Map<String, DryRunStatus> getDryRunStatusMap() {
return ImmutableMap.copyOf(dryRunStatusMap);
return Collections.unmodifiableMap(dryRunStatusMap);
}
/**

View File

@ -17,8 +17,6 @@
package org.openapitools.codegen.ignore;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;
import org.openapitools.codegen.ignore.rules.DirectoryRule;
import org.openapitools.codegen.ignore.rules.Rule;
import org.slf4j.Logger;
@ -26,10 +24,10 @@ import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.nio.file.Files;
import java.util.*;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
/**
* Presents a processing utility for parsing and evaluating files containing common ignore patterns. (.openapi-generator-ignore)
@ -91,7 +89,7 @@ public class CodegenIgnoreProcessor {
if (legacyIgnoreFile.exists() && legacyIgnoreFile.isFile()) {
LOGGER.info(String.format(Locale.ROOT, "Legacy support: '%s' file renamed to '%s'.", legacyIgnoreFile.getName(), targetIgnoreFile.getName()));
try {
Files.move(legacyIgnoreFile, targetIgnoreFile);
Files.move(legacyIgnoreFile.toPath(), targetIgnoreFile.toPath(), REPLACE_EXISTING);
loadFromFile(targetIgnoreFile);
} catch (IOException e) {
LOGGER.error(String.format(Locale.ROOT, "Could not rename file: %s", e.getMessage()));
@ -143,8 +141,8 @@ public class CodegenIgnoreProcessor {
if(this.ignoreFile == null) return true;
File file = new File(this.ignoreFile.getAbsoluteFile().getParentFile().toURI().relativize(targetFile.toURI()).getPath());
Boolean directoryExcluded = false;
Boolean exclude = false;
boolean directoryExcluded = false;
boolean exclude = false;
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
return true;
}
@ -207,10 +205,10 @@ public class CodegenIgnoreProcessor {
/**
* Allows a consumer to manually inspect explicit "inclusion rules". That is, patterns in the ignore file which have been negated.
*
* @return A {@link ImmutableList#copyOf(Collection)} of rules which possibly negate exclusion rules in the ignore file.
* @return A {@link Collections#unmodifiableList(List)} of rules which possibly negate exclusion rules in the ignore file.
*/
public List<Rule> getInclusionRules() {
return ImmutableList.copyOf(inclusionRules);
return Collections.unmodifiableList(inclusionRules);
}
/**
@ -219,9 +217,9 @@ public class CodegenIgnoreProcessor {
*
* NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
*
* @return A {@link ImmutableList#copyOf(Collection)} of rules which define exclusions by patterns in the ignore file.
* @return A {@link Collections#unmodifiableList(List)} of rules which define exclusions by patterns in the ignore file.
*/
public List<Rule> getExclusionRules() {
return ImmutableList.copyOf(exclusionRules);
return Collections.unmodifiableList((exclusionRules));
}
}

View File

@ -17,7 +17,7 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.core.util.Json;
@ -393,7 +393,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true));
}

View File

@ -17,7 +17,7 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.OpenAPI;
@ -307,7 +307,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("multiline_comment_4", new IndentedLambda(4, " ", "///"));
}

View File

@ -1,7 +1,5 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
@ -114,13 +112,12 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
setReservedWordsLowerCase(reservedWordsList);
// These types return isPrimitive=true in templates
languageSpecificPrimitives = Sets.newHashSet(
"String",
"bool",
"int",
"num",
"double"
);
languageSpecificPrimitives = new HashSet<>(5);
languageSpecificPrimitives.add("String");
languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("num");
languageSpecificPrimitives.add("double");
typeMapping = new HashMap<>();
typeMapping.put("Array", "List");
@ -151,18 +148,17 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
typeMapping.put("AnyType", "Object");
// Data types of the above values which are automatically imported
defaultIncludes = Sets.newHashSet(
"String",
"bool",
"int",
"num",
"double",
"List",
"Set",
"Map",
"DateTime",
"Object"
);
defaultIncludes = new HashSet<>();
defaultIncludes.add("String");
defaultIncludes.add("bool");
defaultIncludes.add("int");
defaultIncludes.add("num");
defaultIncludes.add("double");
defaultIncludes.add("List");
defaultIncludes.add("Set");
defaultIncludes.add("Map");
defaultIncludes.add("DateTime");
defaultIncludes.add("Object");
imports.put("String", "dart:core");
imports.put("bool", "dart:core");
@ -345,7 +341,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
// replace all characters that have a mapping but ignore underscores
// append an underscore to each replacement so that it can be camelized
if (name.chars().anyMatch(character -> specialCharReplacements.containsKey("" + ((char) character)))) {
name = escape(name, specialCharReplacements, Lists.newArrayList("_"), "_");
name = escape(name, specialCharReplacements, Collections.singletonList("_"), "_");
}
// remove the rest
name = sanitizeName(name);

View File

@ -30,7 +30,6 @@ import org.slf4j.LoggerFactory;
import java.util.*;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
@ -268,13 +267,13 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
if (!isNullOrEmpty(model.parent)) {
if (StringUtils.isNotBlank(model.parent)) {
parentModels.add(model.parent);
if (!childrenByParent.containsEntry(model.parent, model)) {
childrenByParent.put(model.parent, model);
}
}
if (!isNullOrEmpty(model.parentSchema)) {
if (StringUtils.isNotBlank(model.parentSchema)) {
model.parentSchema = model.parentSchema.toLowerCase(Locale.ROOT);
}
}

View File

@ -16,7 +16,7 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.core.util.Json;
@ -306,7 +306,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true));
}

View File

@ -17,67 +17,12 @@
package org.openapitools.codegen.languages;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.escape;
import static org.openapitools.codegen.utils.StringUtils.underscore;
import java.io.File;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.meta.features.ClientModificationFeature;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
import org.openapitools.codegen.meta.features.SchemaSupportFeature;
import org.openapitools.codegen.meta.features.SecurityFeature;
import org.openapitools.codegen.meta.features.WireFormatFeature;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
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.examples.Example;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.servers.Server;
@ -96,6 +41,7 @@ import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@ -347,7 +293,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (additionalProperties.containsKey(ADDITIONAL_MODEL_TYPE_ANNOTATIONS)) {
String additionalAnnotationsList = additionalProperties.get(ADDITIONAL_MODEL_TYPE_ANNOTATIONS).toString();
this.setAdditionalModelTypeAnnotations(new ArrayList<>(Sets.newHashSet(additionalAnnotationsList.trim().split("\\s*(;|\\r?\\n)\\s*"))));
this.setAdditionalModelTypeAnnotations(Arrays.asList(additionalAnnotationsList.trim().split("\\s*(;|\\r?\\n)\\s*")));
}
if (additionalProperties.containsKey(ADDITIONAL_ENUM_TYPE_ANNOTATIONS)) {

View File

@ -603,6 +603,11 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
return sanitizeKotlinSpecificNames(modified);
}
@Override
public String toEnumName(CodegenProperty property) {
return property.nameInCamelCase;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {

View File

@ -17,7 +17,6 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
@ -271,8 +270,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
private Map<String,String> toImportMap(String... names) {
Map<String,String> result = Maps.newHashMap();
for(String name: names){
Map<String,String> result = new HashMap<>();
for(final String name : names) {
if(needToImport(name)) {
result.put(toModelImport(name), name);
}

View File

@ -315,13 +315,14 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
if (!foundInNewList) {
if (op1.path.equals(op.path)) {
foundInNewList = true;
List<CodegenOperation> currentOtherMethodList = (List<CodegenOperation>) op1.vendorExtensions.get("x-codegen-otherMethods");
final String X_CODEGEN_OTHER_METHODS = "x-codegen-other-methods";
List<CodegenOperation> currentOtherMethodList = (List<CodegenOperation>) op1.vendorExtensions.get(X_CODEGEN_OTHER_METHODS);
if (currentOtherMethodList == null) {
currentOtherMethodList = new ArrayList<CodegenOperation>();
}
op.operationIdCamelCase = op1.operationIdCamelCase;
currentOtherMethodList.add(op);
op1.vendorExtensions.put("x-codegen-other-methods", currentOtherMethodList);
op1.vendorExtensions.put(X_CODEGEN_OTHER_METHODS, currentOtherMethodList);
}
}
}

View File

@ -33,7 +33,6 @@ public class DartClientCodegen extends AbstractDartCodegen {
private final Logger LOGGER = LoggerFactory.getLogger(DartClientCodegen.class);
public static final String SERIALIZATION_LIBRARY_NATIVE = "native_serialization";
public static final String SERIALIZATION_LIBRARY_JSON_SERIALIZABLE = "json_serializable";
public DartClientCodegen() {
super();
@ -43,7 +42,6 @@ public class DartClientCodegen extends AbstractDartCodegen {
final Map<String, String> serializationOptions = new HashMap<>();
serializationOptions.put(SERIALIZATION_LIBRARY_NATIVE, "Use native serializer, backwards compatible");
serializationOptions.put(SERIALIZATION_LIBRARY_JSON_SERIALIZABLE, "Use json_serializable. Experimental and subject to breaking changes without further notice");
serializationLibrary.setEnum(serializationOptions);
cliOptions.add(serializationLibrary);
}
@ -88,15 +86,7 @@ public class DartClientCodegen extends AbstractDartCodegen {
LOGGER.info("Using serialization library {}", serialization_library);
switch (serialization_library) {
case SERIALIZATION_LIBRARY_JSON_SERIALIZABLE:
additionalProperties.put(SERIALIZATION_LIBRARY_JSON_SERIALIZABLE, "true");
// json_serializable requires build.yaml
supportingFiles.add(new SupportingFile("build.yaml.mustache",
"" /* main project dir */,
"build.yaml"));
break;
case SERIALIZATION_LIBRARY_NATIVE: // fall trough to default backwards compatible generator
case SERIALIZATION_LIBRARY_NATIVE: // fall through to default backwards compatible generator
default:
additionalProperties.put(SERIALIZATION_LIBRARY_NATIVE, "true");

View File

@ -420,6 +420,8 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
continue;
}
resultImports.add(i);
} else if (importMapping().containsKey(modelImport)) {
resultImports.add(importMapping().get(modelImport));
} else {
resultImports.add("package:" + pubName + "/src/model/" + underscore(modelImport) + ".dart");
}

View File

@ -63,6 +63,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String MICROPROFILE_FRAMEWORK = "microprofileFramework";
public static final String USE_ABSTRACTION_FOR_FILES = "useAbstractionForFiles";
public static final String DYNAMIC_OPERATIONS = "dynamicOperations";
public static final String GRADLE_PROPERTIES= "gradleProperties";
public static final String PLAY_24 = "play24";
public static final String PLAY_25 = "play25";
@ -111,6 +112,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
protected boolean caseInsensitiveResponseHeaders = false;
protected boolean useAbstractionForFiles = false;
protected boolean dynamicOperations = false;
protected String gradleProperties;
protected String authFolder;
protected String serializationLibrary = null;
@ -154,6 +156,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newString(MICROPROFILE_FRAMEWORK, "Framework for microprofile. Possible values \"kumuluzee\""));
cliOptions.add(CliOption.newBoolean(USE_ABSTRACTION_FOR_FILES, "Use alternative types instead of java.io.File to allow passing bytes without a file on disk. Available on " + RESTTEMPLATE + " library"));
cliOptions.add(CliOption.newBoolean(DYNAMIC_OPERATIONS, "Generate operations dynamically at runtime from an OAS", this.dynamicOperations));
cliOptions.add(CliOption.newString(GRADLE_PROPERTIES, "Append additional Gradle proeprties to the gradle.properties file"));
supportedLibraries.put(JERSEY1, "HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libraries instead.");
supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x");
@ -318,8 +321,14 @@ public class JavaClientCodegen extends AbstractJavaCodegen
}
additionalProperties.put(DYNAMIC_OPERATIONS, dynamicOperations);
if (additionalProperties.containsKey(GRADLE_PROPERTIES)) {
this.setGradleProperties(additionalProperties.get(GRADLE_PROPERTIES).toString());
}
additionalProperties.put(GRADLE_PROPERTIES, gradleProperties);
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String apiFolder = (sourceFolder + '/' + apiPackage).replace(".", "/");
final String modelsFolder = (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar);
authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
//Common files
@ -379,6 +388,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen
if (FEIGN.equals(getLibrary())) {
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
//Templates to decode response headers
supportingFiles.add(new SupportingFile("model/ApiResponse.mustache", modelsFolder, "ApiResponse.java"));
supportingFiles.add(new SupportingFile("ApiResponseDecoder.mustache", invokerFolder, "ApiResponseDecoder.java"));
}
if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || RETROFIT_2.equals(getLibrary()) || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || WEBCLIENT.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) {
@ -423,7 +435,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
if (ProcessUtils.hasHttpSignatureMethods(openAPI)) {
supportingFiles.add(new SupportingFile("auth/HttpSignatureAuth.mustache", authFolder, "HttpSignatureAuth.java"));
}
supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar), "AbstractOpenApiSchema.java"));
supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", modelsFolder, "AbstractOpenApiSchema.java"));
forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON);
// Composed schemas can have the 'additionalProperties' keyword, as specified in JSON schema.
@ -437,7 +449,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
setJava8ModeAndAdditionalProperties(true);
supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java"));
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar), "AbstractOpenApiSchema.java"));
supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", modelsFolder, "AbstractOpenApiSchema.java"));
forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON);
} else if (RESTEASY.equals(getLibrary())) {
setJava8ModeAndAdditionalProperties(true);
@ -980,6 +992,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.dynamicOperations = dynamicOperations;
}
public void setGradleProperties(final String gradleProperties) {
this.gradleProperties= gradleProperties;
}
/**
* Serialization library.
*

View File

@ -38,6 +38,7 @@ import java.util.stream.Collectors;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenConfig;
@ -55,7 +56,6 @@ import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Lambda;
import com.samskivert.mustache.Template;
@ -746,7 +746,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas().put("handleParamValue", new ParameterValueLambda());
}
}

View File

@ -16,7 +16,7 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Lambda;
import com.samskivert.mustache.Template;
@ -437,7 +437,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("escapeDoubleQuote", new EscapeLambda("\"", "\\\""));
}

View File

@ -16,7 +16,6 @@
package org.openapitools.codegen.languages;
import com.google.common.base.Strings;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.*;
@ -522,11 +521,11 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toModelFilename(String name) {
if (!Strings.isNullOrEmpty(modelNamePrefix)) {
if (!StringUtils.isBlank(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!Strings.isNullOrEmpty(modelNameSuffix)) {
if (!StringUtils.isBlank(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}

View File

@ -17,13 +17,13 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.templating.mustache.OnChangeLambda;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.Operation;
@ -85,7 +85,7 @@ public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfi
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("onchange", new OnChangeLambda());
}

View File

@ -360,6 +360,10 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// translate @ for properties (like @type) to at_.
// Otherwise an additional "type" property will leed to duplcates
name = name.replaceAll("^@", "at_");
// replace - with _ e.g. created-at => created_at
name = sanitizeName(name.replaceAll("-", "_"));

View File

@ -420,6 +420,10 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// translate @ for properties (like @type) to at_.
// Otherwise an additional "type" property will leed to duplcates
name = name.replaceAll("^@", "at_");
String sanitizedName = super.sanitizeName(name);
// for reserved word, append _
if (isReservedWord(sanitizedName)) {

View File

@ -16,7 +16,7 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.media.ArraySchema;
@ -216,7 +216,7 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("indented_4", new IndentedLambda(4, " "));
}

View File

@ -17,34 +17,55 @@
package org.openapitools.codegen.languages;
import com.samskivert.mustache.Mustache;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.*;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenResponse;
import org.openapitools.codegen.CodegenSecurity;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.languages.features.BeanValidationFeatures;
import org.openapitools.codegen.languages.features.OptionalFeatures;
import org.openapitools.codegen.languages.features.PerformBeanValidationFeatures;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
import org.openapitools.codegen.meta.features.ParameterFeature;
import org.openapitools.codegen.meta.features.SchemaSupportFeature;
import org.openapitools.codegen.meta.features.SecurityFeature;
import org.openapitools.codegen.meta.features.WireFormatFeature;
import org.openapitools.codegen.templating.mustache.SplitStringLambda;
import org.openapitools.codegen.templating.mustache.TrimWhitespaceLambda;
import org.openapitools.codegen.utils.URLPathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import com.samskivert.mustache.Mustache;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
public class SpringCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures,
OptionalFeatures {
implements BeanValidationFeatures, PerformBeanValidationFeatures, OptionalFeatures {
private final Logger LOGGER = LoggerFactory.getLogger(SpringCodegen.class);
public static final String TITLE = "title";
@ -102,32 +123,16 @@ public class SpringCodegen extends AbstractJavaCodegen
public SpringCodegen() {
super();
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom))
.securityFeatures(EnumSet.of(
SecurityFeature.OAuth2_Implicit,
SecurityFeature.OAuth2_AuthorizationCode,
SecurityFeature.OAuth2_ClientCredentials,
SecurityFeature.OAuth2_Password,
SecurityFeature.ApiKey,
SecurityFeature.BasicAuth
))
.excludeGlobalFeatures(
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.includeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions
)
.includeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism
)
.excludeParameterFeatures(
ParameterFeature.Cookie
)
);
.securityFeatures(EnumSet.of(SecurityFeature.OAuth2_Implicit, SecurityFeature.OAuth2_AuthorizationCode,
SecurityFeature.OAuth2_ClientCredentials, SecurityFeature.OAuth2_Password,
SecurityFeature.ApiKey, SecurityFeature.BasicAuth))
.excludeGlobalFeatures(GlobalFeature.Callbacks, GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling)
.includeGlobalFeatures(GlobalFeature.XMLStructureDefinitions)
.includeSchemaSupportFeatures(SchemaSupportFeature.Polymorphism)
.excludeParameterFeatures(ParameterFeature.Cookie));
outputFolder = "generated-code/javaSpring";
embeddedTemplateDir = templateDir = "JavaSpring";
@ -150,43 +155,67 @@ public class SpringCodegen extends AbstractJavaCodegen
additionalProperties.put("closebrace", CLOSE_BRACE);
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(this.getConfigPackage()));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package (invokerPackage) for generated code").defaultValue(this.getBasePackage()));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.", interfaceOnly));
cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern", delegatePattern));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.", singleContentTypes));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")
.defaultValue(this.getConfigPackage()));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package (invokerPackage) for generated code")
.defaultValue(this.getBasePackage()));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY,
"Whether to generate only API interface stubs without the server files.", interfaceOnly));
cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN,
"Whether to generate the server files using the delegate pattern", delegatePattern));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES,
"Whether to select only one produces/consumes content-type by operation.", singleContentTypes));
updateJava8CliOptions();
cliOptions.add(CliOption.newBoolean(SKIP_DEFAULT_INTERFACE, "Whether to generate default implementations for java8 interfaces", skipDefaultInterface));
cliOptions.add(CliOption.newBoolean(SKIP_DEFAULT_INTERFACE,
"Whether to generate default implementations for java8 interfaces", skipDefaultInterface));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers", async));
cliOptions.add(CliOption.newBoolean(REACTIVE, "wrap responses in Mono/Flux Reactor types (spring-boot only)", reactive));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, HystrixCommand, RxObservable, RxSingle or fully qualified type)"));
cliOptions.add(CliOption.newBoolean(VIRTUAL_SERVICE, "Generates the virtual service. For more details refer - https://github.com/virtualansoftware/virtualan/wiki"));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames", useTags));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations", useBeanValidation));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Use Bean Validation Impl. to perform BeanValidation", performBeanValidation));
cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS, "Skip header parameters in the generated API methods using @ApiImplicitParams annotation.", implicitHeaders));
cliOptions.add(CliOption.newBoolean(OPENAPI_DOCKET_CONFIG, "Generate Spring OpenAPI Docket configuration class.", openapiDocketConfig));
cliOptions.add(CliOption.newBoolean(API_FIRST, "Generate the API from the OAI spec at server compile time (API first approach)", apiFirst));
cliOptions.add(CliOption.newBoolean(USE_OPTIONAL, "Use Optional container for optional parameters", useOptional));
cliOptions.add(CliOption.newBoolean(HATEOAS, "Use Spring HATEOAS library to allow adding HATEOAS links", hateoas));
cliOptions.add(CliOption.newBoolean(RETURN_SUCCESS_CODE, "Generated server returns 2xx code", returnSuccessCode));
cliOptions.add(CliOption.newBoolean(UNHANDLED_EXCEPTION_HANDLING, "Declare operation methods to throw a generic exception and allow unhandled exceptions (useful for Spring `@ControllerAdvice` directives).", unhandledException));
cliOptions.add(CliOption.newBoolean(REACTIVE, "wrap responses in Mono/Flux Reactor types (spring-boot only)",
reactive));
cliOptions.add(new CliOption(RESPONSE_WRAPPER,
"wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, RxObservable, RxSingle or fully qualified type)"));
cliOptions.add(CliOption.newBoolean(VIRTUAL_SERVICE,
"Generates the virtual service. For more details refer - https://github.com/virtualansoftware/virtualan/wiki"));
cliOptions.add(
CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames", useTags));
cliOptions
.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations", useBeanValidation));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION,
"Use Bean Validation Impl. to perform BeanValidation", performBeanValidation));
cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS,
"Skip header parameters in the generated API methods using @ApiImplicitParams annotation.",
implicitHeaders));
cliOptions.add(CliOption.newBoolean(OPENAPI_DOCKET_CONFIG,
"Generate Spring OpenAPI Docket configuration class.", openapiDocketConfig));
cliOptions.add(CliOption.newBoolean(API_FIRST,
"Generate the API from the OAI spec at server compile time (API first approach)", apiFirst));
cliOptions
.add(CliOption.newBoolean(USE_OPTIONAL, "Use Optional container for optional parameters", useOptional));
cliOptions.add(
CliOption.newBoolean(HATEOAS, "Use Spring HATEOAS library to allow adding HATEOAS links", hateoas));
cliOptions
.add(CliOption.newBoolean(RETURN_SUCCESS_CODE, "Generated server returns 2xx code", returnSuccessCode));
cliOptions.add(CliOption.newBoolean(UNHANDLED_EXCEPTION_HANDLING,
"Declare operation methods to throw a generic exception and allow unhandled exceptions (useful for Spring `@ControllerAdvice` directives).",
unhandledException));
supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY,
"Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
setLibrary(SPRING_BOOT);
CliOption library = new CliOption(CodegenConstants.LIBRARY, CodegenConstants.LIBRARY_DESC).defaultValue(SPRING_BOOT);
final CliOption library = new CliOption(CodegenConstants.LIBRARY, CodegenConstants.LIBRARY_DESC)
.defaultValue(SPRING_BOOT);
library.setEnum(supportedLibraries);
cliOptions.add(library);
}
private void updateJava8CliOptions() {
CliOption option = cliOptions.stream().filter(o -> JAVA_8.equals(o.getOpt())).findFirst()
final CliOption option = cliOptions.stream().filter(o -> JAVA_8.equals(o.getOpt())).findFirst()
.orElseThrow(() -> new RuntimeException("Missing java8 option"));
Map<String, String> java8ModeOptions = option.getEnum();
java8ModeOptions.put("true", "Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used. IMPORTANT: This option has been deprecated as Java 8 is the default.");
final Map<String, String> java8ModeOptions = option.getEnum();
java8ModeOptions.put("true",
"Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used. IMPORTANT: This option has been deprecated as Java 8 is the default.");
}
@Override
@ -207,25 +236,27 @@ public class SpringCodegen extends AbstractJavaCodegen
@Override
public void processOpts() {
List<Pair<String, String>> configOptions = additionalProperties.entrySet().stream()
final List<Pair<String, String>> configOptions = additionalProperties.entrySet().stream()
.filter(e -> !Arrays.asList(API_FIRST, "hideGenerationTimestamp").contains(e.getKey()))
.filter(e -> cliOptions.stream().map(CliOption::getOpt).anyMatch(opt -> opt.equals(e.getKey())))
.map(e -> Pair.of(e.getKey(), e.getValue().toString()))
.collect(Collectors.toList());
.map(e -> Pair.of(e.getKey(), e.getValue().toString())).collect(Collectors.toList());
additionalProperties.put("configOptions", configOptions);
// Process java8 option before common java ones to change the default dateLibrary to java8.
// Process java8 option before common java ones to change the default
// dateLibrary to java8.
LOGGER.info("----------------------------------");
if (additionalProperties.containsKey(JAVA_8)) {
this.setJava8(Boolean.parseBoolean(additionalProperties.get(JAVA_8).toString()));
additionalProperties.put(JAVA_8, java8);
LOGGER.warn("java8 option has been deprecated as it's set to true by default (JDK7 support has been deprecated)");
LOGGER.warn(
"java8 option has been deprecated as it's set to true by default (JDK7 support has been deprecated)");
}
if (this.java8 && !additionalProperties.containsKey(DATE_LIBRARY)) {
if (java8 && !additionalProperties.containsKey(DATE_LIBRARY)) {
setDateLibrary("java8");
}
if (!additionalProperties.containsKey(BASE_PACKAGE) && additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
if (!additionalProperties.containsKey(BASE_PACKAGE)
&& additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
// set invokerPackage as basePackage:
this.setBasePackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
additionalProperties.put(BASE_PACKAGE, basePackage);
@ -273,7 +304,8 @@ public class SpringCodegen extends AbstractJavaCodegen
}
if (additionalProperties.containsKey(SKIP_DEFAULT_INTERFACE)) {
this.setSkipDefaultInterface(Boolean.parseBoolean(additionalProperties.get(SKIP_DEFAULT_INTERFACE).toString()));
this.setSkipDefaultInterface(
Boolean.parseBoolean(additionalProperties.get(SKIP_DEFAULT_INTERFACE).toString()));
}
if (additionalProperties.containsKey(ASYNC)) {
@ -316,7 +348,8 @@ public class SpringCodegen extends AbstractJavaCodegen
}
if (additionalProperties.containsKey(OPENAPI_DOCKET_CONFIG)) {
this.setOpenapiDocketConfig(Boolean.parseBoolean(additionalProperties.get(OPENAPI_DOCKET_CONFIG).toString()));
this.setOpenapiDocketConfig(
Boolean.parseBoolean(additionalProperties.get(OPENAPI_DOCKET_CONFIG).toString()));
}
if (additionalProperties.containsKey(API_FIRST)) {
@ -332,7 +365,8 @@ public class SpringCodegen extends AbstractJavaCodegen
}
if (additionalProperties.containsKey(UNHANDLED_EXCEPTION_HANDLING)) {
this.setUnhandledException(Boolean.parseBoolean(additionalProperties.get(UNHANDLED_EXCEPTION_HANDLING).toString()));
this.setUnhandledException(
Boolean.parseBoolean(additionalProperties.get(UNHANDLED_EXCEPTION_HANDLING).toString()));
}
additionalProperties.put(UNHANDLED_EXCEPTION_HANDLING, this.isUnhandledException());
@ -343,9 +377,9 @@ public class SpringCodegen extends AbstractJavaCodegen
writePropertyBack(USE_OPTIONAL, useOptional);
}
if (this.interfaceOnly && this.delegatePattern) {
if (this.java8) {
this.delegateMethod = true;
if (interfaceOnly && delegatePattern) {
if (java8) {
delegateMethod = true;
additionalProperties.put("delegate-method", true);
} else {
throw new IllegalArgumentException(
@ -357,28 +391,36 @@ public class SpringCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
if (!this.interfaceOnly) {
if (!interfaceOnly) {
if (SPRING_BOOT.equals(library)) {
supportingFiles.add(new SupportingFile("openapi2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "OpenAPI2SpringBoot.java"));
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator),
"OpenAPI2SpringBoot.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator),
"RFC3339DateFormat.java"));
}
if (SPRING_MVC_LIBRARY.equals(library)) {
supportingFiles.add(new SupportingFile("webApplication.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"WebApplication.java"));
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"WebMvcConfiguration.java"));
supportingFiles.add(new SupportingFile("openapiUiConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "OpenAPIUiConfiguration.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"OpenAPIUiConfiguration.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"RFC3339DateFormat.java"));
}
if (SPRING_CLOUD_LIBRARY.equals(library)) {
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"ApiKeyRequestInterceptor.java"));
supportingFiles.add(new SupportingFile("clientConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"ClientConfiguration.java"));
apiTemplateFiles.put("apiClient.mustache", "Client.java");
if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
additionalProperties.put(SINGLE_CONTENT_TYPES, "true");
@ -389,18 +431,21 @@ public class SpringCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("application.mustache",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
if (!this.reactive && !this.apiFirst) {
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"HomeController.java"));
if (!reactive && !apiFirst) {
supportingFiles.add(new SupportingFile("openapiDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "OpenAPIDocumentationConfig.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"OpenAPIDocumentationConfig.java"));
} else {
supportingFiles.add(new SupportingFile("openapi.mustache",
("src/main/resources").replace("/", java.io.File.separator), "openapi.yaml"));
}
}
} else if (this.openapiDocketConfig && !SPRING_CLOUD_LIBRARY.equals(library) && !this.reactive && !this.apiFirst) {
} else if (openapiDocketConfig && !SPRING_CLOUD_LIBRARY.equals(library) && !reactive && !apiFirst) {
supportingFiles.add(new SupportingFile("openapiDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "OpenAPIDocumentationConfig.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"OpenAPIDocumentationConfig.java"));
}
if (!SPRING_CLOUD_LIBRARY.equals(library)) {
@ -408,73 +453,69 @@ public class SpringCodegen extends AbstractJavaCodegen
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiUtil.java"));
}
if (this.apiFirst) {
if (apiFirst) {
apiTemplateFiles.clear();
modelTemplateFiles.clear();
}
if ("threetenbp".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("customInstantDeserializer.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "CustomInstantDeserializer.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"CustomInstantDeserializer.java"));
if (SPRING_BOOT.equals(library) || SPRING_CLOUD_LIBRARY.equals(library)) {
supportingFiles.add(new SupportingFile("jacksonConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "JacksonConfiguration.java"));
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator),
"JacksonConfiguration.java"));
}
}
if ((!this.delegatePattern && this.java8) || this.delegateMethod) {
if ((!delegatePattern && java8) || delegateMethod) {
additionalProperties.put("jdk8-no-delegate", true);
}
if (this.delegatePattern && !this.delegateMethod) {
if (delegatePattern && !delegateMethod) {
additionalProperties.put("isDelegate", "true");
apiTemplateFiles.put("apiDelegate.mustache", "Delegate.java");
}
if (this.java8) {
if (java8) {
additionalProperties.put("javaVersion", "1.8");
if (SPRING_CLOUD_LIBRARY.equals(library)) {
additionalProperties.put("jdk8-default-interface", false);
} else {
additionalProperties.put("jdk8-default-interface", !this.skipDefaultInterface);
additionalProperties.put("jdk8-default-interface", !skipDefaultInterface);
}
additionalProperties.put("jdk8", true);
if (this.async) {
if (async) {
additionalProperties.put(RESPONSE_WRAPPER, "CompletableFuture");
}
if (this.reactive) {
if (reactive) {
additionalProperties.put(RESPONSE_WRAPPER, "Mono");
}
} else if (this.async) {
} else if (async) {
additionalProperties.put(RESPONSE_WRAPPER, "Callable");
}
if (!this.apiFirst && !this.reactive) {
if (!apiFirst && !reactive) {
additionalProperties.put("useSpringfox", true);
}
// Some well-known Spring or Spring-Cloud response wrappers
if (isNotEmpty(this.responseWrapper)) {
if (isNotEmpty(responseWrapper)) {
additionalProperties.put("jdk8", false);
additionalProperties.put("jdk8-default-interface", false);
switch (this.responseWrapper) {
switch (responseWrapper) {
case "Future":
case "Callable":
case "CompletableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent." + this.responseWrapper);
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent." + responseWrapper);
break;
case "ListenableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture");
break;
case "DeferredResult":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.async.DeferredResult");
break;
case "HystrixCommand":
additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand");
additionalProperties.put(RESPONSE_WRAPPER,
"org.springframework.web.context.request.async.DeferredResult");
break;
case "RxObservable":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Observable");
@ -488,10 +529,10 @@ public class SpringCodegen extends AbstractJavaCodegen
}
// add lambda for mustache templates
additionalProperties.put("lambdaRemoveDoubleQuote",
(Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement(""))));
additionalProperties.put("lambdaEscapeDoubleQuote",
(Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement("\\\""))));
additionalProperties.put("lambdaRemoveDoubleQuote", (Mustache.Lambda) (fragment, writer) -> writer
.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement(""))));
additionalProperties.put("lambdaEscapeDoubleQuote", (Mustache.Lambda) (fragment, writer) -> writer
.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement("\\\""))));
additionalProperties.put("lambdaRemoveLineBreak",
(Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\\r|\\n", "")));
@ -501,13 +542,14 @@ public class SpringCodegen extends AbstractJavaCodegen
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co,
Map<String, List<CodegenOperation>> operations) {
if ((SPRING_BOOT.equals(library) || SPRING_MVC_LIBRARY.equals(library)) && !useTags) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
final int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
@ -517,7 +559,7 @@ public class SpringCodegen extends AbstractJavaCodegen
} else {
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.computeIfAbsent(basePath, k -> new ArrayList<>());
final List<CodegenOperation> opList = operations.computeIfAbsent(basePath, k -> new ArrayList<>());
opList.add(co);
co.baseName = basePath;
} else {
@ -528,10 +570,9 @@ public class SpringCodegen extends AbstractJavaCodegen
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
/* TODO the following logic should not need anymore in OAS 3.0
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
/*
* TODO the following logic should not need anymore in OAS 3.0 if
* ("/".equals(swagger.getBasePath())) { swagger.setBasePath(""); }
*/
if (!additionalProperties.containsKey(TITLE)) {
@ -551,25 +592,25 @@ public class SpringCodegen extends AbstractJavaCodegen
}
if (!additionalProperties.containsKey(SERVER_PORT)) {
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
this.additionalProperties.put(SERVER_PORT, URLPathUtils.getPort(url, 8080));
final URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
additionalProperties.put(SERVER_PORT, URLPathUtils.getPort(url, 8080));
}
if (openAPI.getPaths() != null) {
for (Map.Entry<String, PathItem> openAPIGetPathsEntry : openAPI.getPaths().entrySet()) {
String pathname = openAPIGetPathsEntry.getKey();
PathItem path = openAPIGetPathsEntry.getValue();
for (final Map.Entry<String, PathItem> openAPIGetPathsEntry : openAPI.getPaths().entrySet()) {
final String pathname = openAPIGetPathsEntry.getKey();
final PathItem path = openAPIGetPathsEntry.getValue();
if (path.readOperations() != null) {
for (Operation operation : path.readOperations()) {
for (final Operation operation : path.readOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
final List<Map<String, String>> tags = new ArrayList<>();
for (final String tag : operation.getTags()) {
final Map<String, String> value = new HashMap<>();
value.put("tag", tag);
tags.add(value);
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
final String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.addExtension("x-tags", tags);
@ -582,11 +623,11 @@ public class SpringCodegen extends AbstractJavaCodegen
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
final Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
final List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (final CodegenOperation operation : ops) {
List<CodegenResponse> responses = operation.responses;
final List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (final CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
@ -636,26 +677,27 @@ public class SpringCodegen extends AbstractJavaCodegen
/**
* @param returnType The return type that needs to be converted
* @param dataTypeAssigner An object that will assign the data to the respective fields in the model.
* @param dataTypeAssigner An object that will assign the data to the respective
* fields in the model.
*/
private void doDataTypeAssignment(String returnType, DataTypeAssigner dataTypeAssigner) {
final String rt = returnType;
if (rt == null) {
dataTypeAssigner.setReturnType("Void");
} else if (rt.startsWith("List")) {
int end = rt.lastIndexOf(">");
final int end = rt.lastIndexOf(">");
if (end > 0) {
dataTypeAssigner.setReturnType(rt.substring("List<".length(), end).trim());
dataTypeAssigner.setReturnContainer("List");
}
} else if (rt.startsWith("Map")) {
int end = rt.lastIndexOf(">");
final int end = rt.lastIndexOf(">");
if (end > 0) {
dataTypeAssigner.setReturnType(rt.substring("Map<".length(), end).split(",", 2)[1].trim());
dataTypeAssigner.setReturnContainer("Map");
}
} else if (rt.startsWith("Set")) {
int end = rt.lastIndexOf(">");
final int end = rt.lastIndexOf(">");
if (end > 0) {
dataTypeAssigner.setReturnType(rt.substring("Set<".length(), end).trim());
dataTypeAssigner.setReturnContainer("Set");
@ -675,7 +717,7 @@ public class SpringCodegen extends AbstractJavaCodegen
final ArrayList<CodegenParameter> copy = new ArrayList<>(allParams);
allParams.clear();
for (CodegenParameter p : copy) {
for (final CodegenParameter p : copy) {
if (!p.isHeaderParam) {
allParams.add(p);
}
@ -686,9 +728,9 @@ public class SpringCodegen extends AbstractJavaCodegen
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateYAMLSpecFile(objs);
if (SPRING_CLOUD_LIBRARY.equals(library)) {
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
final List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
for (final CodegenSecurity authMethod : authMethods) {
authMethod.name = camelize(sanitizeName(authMethod.name), true);
}
}
@ -724,7 +766,8 @@ public class SpringCodegen extends AbstractJavaCodegen
if (example == null) {
example = "/path/to/file";
}
example = "new org.springframework.core.io.FileSystemResource(new java.io.File(\"" + escapeText(example) + "\"))";
example = "new org.springframework.core.io.FileSystemResource(new java.io.File(\"" + escapeText(example)
+ "\"))";
p.example = example;
} else {
super.setParameterExampleValue(p);
@ -740,7 +783,7 @@ public class SpringCodegen extends AbstractJavaCodegen
}
public String getConfigPackage() {
return this.configPackage;
return configPackage;
}
public boolean isUnhandledException() {
@ -752,7 +795,7 @@ public class SpringCodegen extends AbstractJavaCodegen
}
public String getBasePackage() {
return this.basePackage;
return basePackage;
}
public void setInterfaceOnly(boolean interfaceOnly) {
@ -767,9 +810,13 @@ public class SpringCodegen extends AbstractJavaCodegen
this.singleContentTypes = singleContentTypes;
}
public void setSkipDefaultInterface(boolean skipDefaultInterface) { this.skipDefaultInterface = skipDefaultInterface; }
public void setSkipDefaultInterface(boolean skipDefaultInterface) {
this.skipDefaultInterface = skipDefaultInterface;
}
public void setJava8(boolean java8) { this.java8 = java8; }
public void setJava8(boolean java8) {
this.java8 = java8;
}
public void setVirtualService(boolean virtualService) {
this.virtualService = virtualService;
@ -852,15 +899,15 @@ public class SpringCodegen extends AbstractJavaCodegen
objs = super.postProcessModelsEnum(objs);
// Add imports for Jackson
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
final List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
final List<Object> models = (List<Object>) objs.get("models");
for (final Object _mo : models) {
final Map<String, Object> mo = (Map<String, Object>) _mo;
final CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
final Map<String, String> item = new HashMap<>();
item.put("import", importMapping.get("JsonValue"));
imports.add(item);
}
@ -869,10 +916,12 @@ public class SpringCodegen extends AbstractJavaCodegen
return objs;
}
@Override
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
@Override
public void setPerformBeanValidation(boolean performBeanValidation) {
this.performBeanValidation = performBeanValidation;
}

View File

@ -314,7 +314,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
ExtendedCodegenModel cm = (ExtendedCodegenModel) mo.get("model");
cm.imports = new TreeSet(cm.imports);
cm.imports = new TreeSet<>(cm.imports);
this.processCodeGenModel(cm);
}

View File

@ -17,7 +17,6 @@
package org.openapitools.codegen.utils;
import com.google.common.collect.ImmutableMap;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.ServerVariable;
@ -59,7 +58,7 @@ public class URLPathUtils {
variables = new ServerVariables();
}
Map<String, String> userVariables = userDefinedVariables == null ? new HashMap<>() : ImmutableMap.copyOf(userDefinedVariables);
Map<String, String> userVariables = userDefinedVariables == null ? new HashMap<>() : Collections.unmodifiableMap(userDefinedVariables);
if (StringUtils.isNotBlank(url)) {
url = extractUrl(server, url, variables, userVariables);

View File

@ -21,7 +21,12 @@
Building the API client library requires:
1. Java {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}+
{{#jersey2}}
2. Maven (3.8.3+)/Gradle (7.2+)
{{/jersey2}}
{{^jersey2}}
2. Maven/Gradle
{{/jersey2}}
## Installation
@ -57,7 +62,14 @@ Add this dependency to your project's POM:
Add this dependency to your project's build file:
```groovy
compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}"
repositories {
mavenCentral() // Needed if the '{{{artifactId}}}' jar has been published to maven central.
mavenLocal() // Needed if the '{{{artifactId}}}' jar has been published to the local maven repo.
}
dependencies {
implementation "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}"
}
```
### Others

View File

@ -6,8 +6,7 @@ version = '{{artifactVersion}}'
buildscript {
repositories {
maven { url "https://repo1.maven.org/maven2" }
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.+'
@ -16,8 +15,7 @@ buildscript {
}
repositories {
maven { url "https://repo1.maven.org/maven2" }
jcenter()
mavenCentral()
}
if(hasProperty('target') && target == 'android') {
@ -84,7 +82,7 @@ if(hasProperty('target') && target == 'android') {
} else {
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
@ -95,9 +93,13 @@ if(hasProperty('target') && target == 'android') {
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
publishing {
publications {
maven(MavenPublication) {
artifactId = '{{artifactId}}'
from components.java
}
}
}

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -1,2 +1,9 @@
# Uncomment to build for Android
# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator).
# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option.
#
# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties
# For example, uncomment below to build for Android
#target = android
{{#gradleProperties}}
{{{.}}}
{{/gradleProperties}}

View File

@ -33,7 +33,7 @@ set APP_HOME=%DIRNAME%
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

View File

@ -1,7 +1,7 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright 2015 the original author or authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -17,67 +17,101 @@
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
@ -106,80 +140,95 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -35,6 +35,7 @@ import feign.slf4j.Slf4jLogger;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.HttpBearerAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.ApiResponseDecoder;
{{#hasOAuthMethods}}
import {{invokerPackage}}.auth.ApiErrorDecoder;
@ -63,7 +64,7 @@ public class ApiClient {
feignBuilder = Feign.builder()
.client(new OkHttpClient())
.encoder(new FormEncoder(new JacksonEncoder(objectMapper)))
.decoder(new JacksonDecoder(objectMapper))
.decoder(new ApiResponseDecoder(objectMapper))
{{#hasOAuthMethods}}
.errorDecoder(new ApiErrorDecoder())
.retryer(new Retryer.Default(0, 0, 2))

View File

@ -0,0 +1,38 @@
package {{invokerPackage}};
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.Types;
import feign.jackson.JacksonDecoder;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import {{modelPackage}}.ApiResponse;
public class ApiResponseDecoder extends JacksonDecoder {
public ApiResponseDecoder(ObjectMapper mapper) {
super(mapper);
}
@Override
public Object decode(Response response, Type type) throws IOException {
Map<String, Collection<String>> responseHeaders = Collections.unmodifiableMap(response.headers());
//Detects if the type is an instance of the parameterized class ApiResponse
Type responseBodyType;
if (Types.getRawType(type).isAssignableFrom(ApiResponse.class)) {
//The ApiResponse class has a single type parameter, the Dto class itself
responseBodyType = ((ParameterizedType) type).getActualTypeArguments()[0];
Object body = super.decode(response, responseBodyType);
return new ApiResponse(response.status(), responseHeaders, body);
} else {
//The response is not encapsulated in the ApiResponse, decode the Dto as normal
return super.decode(response, type);
}
}
}

View File

@ -5,6 +5,7 @@ import {{invokerPackage}}.EncodingUtils;
{{#legacyDates}}
import {{invokerPackage}}.ParamExpander;
{{/legacyDates}}
import {{modelPackage}}.ApiResponse;
{{#imports}}import {{import}};
{{/imports}}
@ -49,8 +50,39 @@ public interface {{classname}} extends ApiClient.Api {
{{/-last}}{{/headerParams}}
})
{{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{paramName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{#hasQueryParams}}
/**
* {{summary}}
* Similar to <code>{{operationId}}</code> but it also returns the http response headers .
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}
{{/allParams}}
{{#returnType}}
* @return A ApiResponse that wraps the response boyd and the http headers.
{{/returnType}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
@RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{^-last}}&{{/-last}}{{/queryParams}}")
@Headers({
{{#vendorExtensions.x-contentType}} "Content-Type: {{vendorExtensions.x-contentType}}",
{{/vendorExtensions.x-contentType}} "Accept: {{vendorExtensions.x-accepts}}",{{#headerParams}}
"{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{^-last}},
{{/-last}}{{/headerParams}}
})
ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{nickname}}WithHttpInfo({{#allParams}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{paramName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{#hasQueryParams}}
/**
* {{summary}}
* {{notes}}
@ -94,6 +126,47 @@ public interface {{classname}} extends ApiClient.Api {
})
{{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isQueryParam}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{paramName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}, {{/isQueryParam}}{{/allParams}}@QueryMap(encoded=true) Map<String, Object> queryParams);
/**
* {{summary}}
* {{notes}}
* Note, this is equivalent to the other <code>{{operationId}}</code> that receives the query parameters as a map,
* but this one also exposes the Http response headers
{{#allParams}}
{{^isQueryParam}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}
{{/isQueryParam}}
{{/allParams}}
* @param queryParams Map of query parameters as name-value pairs
* <p>The following elements may be specified in the query map:</p>
* <ul>
{{#queryParams}}
* <li>{{paramName}} - {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}</li>
{{/queryParams}}
* </ul>
{{#returnType}}
* @return {{.}}
{{/returnType}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
@RequestLine("{{httpMethod}} {{{path}}}?{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{^-last}}&{{/-last}}{{/queryParams}}")
@Headers({
{{#vendorExtensions.x-contentType}} "Content-Type: {{vendorExtensions.x-contentType}}",
{{/vendorExtensions.x-contentType}} "Accept: {{vendorExtensions.x-accepts}}",{{#headerParams}}
"{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{^-last}},
{{/-last}}{{/headerParams}}
})
ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{nickname}}WithHttpInfo({{#allParams}}{{^isQueryParam}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{paramName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}, {{/isQueryParam}}{{/allParams}}@QueryMap(encoded=true) Map<String, Object> queryParams);
/**
* A convenience class for generating query parameters for the
* <code>{{operationId}}</code> method in a fluent style.

View File

@ -5,7 +5,7 @@ import feign.RetryableException;
import feign.codec.ErrorDecoder;
/**
* Error decoder that makes the HTTP 401 and 403 Retryable. Sometimes the 401 or 402 may indicate an expired token
* Error decoder that makes the HTTP 401 and 403 Retryable. Sometimes the 401 or 403 may indicate an expired token
* All the other HTTP status are handled by the {@link feign.codec.ErrorDecoder.Default} decoder
*/
public class ApiErrorDecoder implements ErrorDecoder {

View File

@ -0,0 +1,43 @@
package {{modelPackage}};
import java.util.Map;
import java.util.List;
public class ApiResponse<T>{
final private int statusCode;
final private Map<String, List<String>> headers;
final private T data;
/**
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers) {
this(statusCode, headers, null);
}
/**
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
* @param data The object deserialized from response bod
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) {
this.statusCode = statusCode;
this.headers = headers;
this.data = data;
}
public int getStatusCode() {
return statusCode;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public T getData() {
return data;
}
}

View File

@ -6,8 +6,7 @@ version = '{{artifactVersion}}'
buildscript {
repositories {
maven { url "https://repo1.maven.org/maven2" }
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.+'
@ -16,10 +15,9 @@ buildscript {
}
repositories {
jcenter()
mavenCentral()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
@ -83,7 +81,7 @@ if(hasProperty('target') && target == 'android') {
} else {
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -93,9 +91,13 @@ if(hasProperty('target') && target == 'android') {
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
publishing {
publications {
maven(MavenPublication) {
artifactId = '{{artifactId}}'
from components.java
}
}
}

View File

@ -142,7 +142,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);

View File

@ -21,7 +21,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
{{#authMethods}}
{{#isOAuth}}
import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
{{#isApplication}}

View File

@ -22,7 +22,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<version>2.5.5</version>
</parent>
{{/parentOverridden}}
<build>
@ -35,7 +35,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Finchley.SR1</version>
<version>2020.0.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -64,6 +64,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
{{#withXml}}
<!-- XML processing: Jackson -->
@ -98,7 +99,7 @@
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
{{^parentOverridden}}
<version>0.1.0</version>
<version>0.2.1</version>
{{/parentOverridden}}
</dependency>
{{/openApiNullable}}
@ -126,7 +127,7 @@
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>

View File

@ -2,10 +2,10 @@ FROM alpine:3.12.0
RUN apk add --update --no-cache curl ca-certificates bash bash-completion zsh curl git vim ncurses util-linux
ADD {{scriptName}} /usr/bin/{{scriptName}}
ADD _{{scriptName}} /usr/local/share/zsh/site-functions/_{{scriptName}}
ADD {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}}
RUN chmod 755 /usr/bin/{{scriptName}}
ADD {{x-codegen-script-name}} /usr/bin/{{x-codegen-script-name}}
ADD _{{x-codegen-script-name}} /usr/local/share/zsh/site-functions/_{{x-codegen-script-name}}
ADD {{x-codegen-script-name}}.bash-completion /etc/bash-completion.d/{{x-codegen-script-name}}
RUN chmod 755 /usr/bin/{{x-codegen-script-name}}
#
# Install oh-my-zsh
@ -17,7 +17,7 @@ RUN sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh
#
RUN echo '\n\
. /etc/bash_completion\n\
source /etc/bash-completion.d/{{scriptName}}\n\
source /etc/bash-completion.d/{{x-codegen-script-name}}\n\
' >> ~/.bashrc
#
@ -51,13 +51,13 @@ For convenience, you can export the following environment variables:\n\
$(tput setaf 7)Basic usage:$(tput sgr0)\n\
\n\
$(tput setaf 3)Print the list of operations available on the service$(tput sgr0)\n\
$ {{scriptName}} -h\n\
$ {{x-codegen-script-name}} -h\n\
\n\
$(tput setaf 3)Print the service description$(tput sgr0)\n\
$ {{scriptName}} --about\n\
$ {{x-codegen-script-name}} --about\n\
\n\
$(tput setaf 3)Print detailed information about specific operation$(tput sgr0)\n\
$ {{scriptName}} <operationId> -h\n\
$ {{x-codegen-script-name}} <operationId> -h\n\
\n\
By default you are logged into Zsh with full autocompletion for your REST API,\n\
but you can switch to Bash, where basic autocompletion is also supported.\n\

View File

@ -1,3 +1,5 @@
# C++ Qt API client
# {{artifactId}}
{{appName}}
@ -16,55 +18,18 @@
*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)*
## Licence
{{licenseInfo}}
for more information visit [{{licenseInfo}}]({{licenseUrl}})
## Requirements
Building the API client library requires:
1. Java {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}}+
2. Maven/Gradle
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn clean install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn clean deploy
```
Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information.
### Generate manually
At first generate the JAR by executing:
```shell
mvn clean package
```
Use the Jar file to generate the Qt Client:
```shell
java -jar target/openapi-generator-cli.jar generate -i <yourOpenApiFile> -g cpp-qt-client -o <outputDir>
```
1. CMake 3.2+
2. Qt
3. C++ Compiler
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
example.h:
```c++
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
#include <iostream>
@ -82,8 +47,8 @@ public slots:
};
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
example.cpp:
example.cpp:
```c++
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
#include "../client/{{{classname}}}.h"
@ -132,25 +97,11 @@ void Example::exampleFunction1(){
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{commonPath}}{{path}} | {{summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Documentation for Servers
Parameterized Servers are supported. Define a server in the API for each endpoint with arbitrary numbers of variables:
```
```yaml
servers:
- url: http://{server}:{port}/{basePath}
description: Description of the Server
@ -170,7 +121,7 @@ servers:
default: v1
```
To change the default variable, use this function in each Api:
```
```c++
int setDefaultServerValue(int serverIndex,const QString &operation, const QString &variable,const QString &val);
```
The parameter "serverIndex" will choose a server from the server list for each endpoint. There is always at least one server with index 0. The Parameter "operation" should be the desired endpoint operationid.
@ -178,12 +129,12 @@ Variable is the name of the variable you wish to change and the value is the new
The function will return -1 when the variable does not exists, -2 if value is not defined in the variable enum and -3 if the operation is not found.
If your endpoint has multiple server objects in the servers array, you can set the server that will be used with this function:
```
```c++
void setServerIndex(const QString &operation, int serverIndex);
```
Parameter "operation" should be your operationid. "serverIndex" is the index you want to set as your default server. The function will check if there is a server with your index.
Here is an example of multiple servers in the servers array. The first server will have index 0 and the second will have index 1.
```
```yaml
servers:
- url: http://{server}:8080/
description: Description of the Server
@ -197,7 +148,6 @@ servers:
- url: https://localhost:8080/v1
```
## Documentation for Authorization
{{^authMethods}}All endpoints do not require authorization.
@ -233,3 +183,7 @@ servers:
{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}}
{{/-last}}{{/apis}}{{/apiInfo}}
## License
{{licenseInfo}} for more information visit [{{licenseInfo}}]({{licenseUrl}})

View File

@ -51,6 +51,7 @@ public:
static utility::string_t parameterToString(float value);
static utility::string_t parameterToString(double value);
static utility::string_t parameterToString(const utility::datetime &value);
static utility::string_t parameterToString(bool value);
template<class T>
static utility::string_t parameterToString(const std::vector<T>& value);
template<class T>

View File

@ -79,6 +79,13 @@ utility::string_t ApiClient::parameterToString(const utility::datetime &value)
return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601));
}
utility::string_t ApiClient::parameterToString(bool value)
{
std::stringstream valueAsStringStream;
valueAsStringStream << std::boolalpha << value;
return utility::conversions::to_string_t(valueAsStringStream.str());
}
pplx::task<web::http::http_response> ApiClient::callApi(
const utility::string_t& path,
const utility::string_t& method,

View File

@ -10,6 +10,55 @@ namespace {{this}} {
{{#isEnum}}
namespace
{
using EnumUnderlyingType = {{#isNumeric}}int64_t{{/isNumeric}}{{^isNumeric}}utility::string_t{{/isNumeric}};
{{classname}}::e{{classname}} toEnum(const EnumUnderlyingType& val)
{
{{#allowableValues}}
{{#isNumeric}}
switch (val)
{
{{#enumVars}}
case {{value}}:
return {{classname}}::e{{classname}}::{{classname}}_{{name}};
{{#-last}}
default:
break;
{{/-last}}
{{/enumVars}}
}
{{/isNumeric}}
{{^isNumeric}}
{{#enumVars}}
if (val == utility::conversions::to_string_t(U("{{{value}}}")))
return {{classname}}::e{{classname}}::{{classname}}_{{name}};
{{/enumVars}}
{{/isNumeric}}
{{/allowableValues}}
return {};
}
EnumUnderlyingType fromEnum({{classname}}::e{{classname}} e)
{
{{#allowableValues}}
switch (e)
{
{{#enumVars}}
case {{classname}}::e{{classname}}::{{classname}}_{{name}}:
return {{#isNumeric}}{{value}}{{/isNumeric}}{{^isNumeric}}U("{{value}}"){{/isNumeric}};
{{#-last}}
default:
break;
{{/-last}}
{{/enumVars}}
}
{{/allowableValues}}
return {};
}
}
{{classname}}::{{classname}}()
{
}
@ -25,57 +74,45 @@ void {{classname}}::validate()
web::json::value {{classname}}::toJson() const
{
web::json::value val = web::json::value::object();
{{#allowableValues}}{{#enumVars}}
if (m_value == e{{classname}}::{{classname}}_{{name}}) val = web::json::value::string(U({{{value}}}));{{/enumVars}}{{/allowableValues}}
return val;
auto val = fromEnum(m_value);
return web::json::value(val);
}
bool {{classname}}::fromJson(const web::json::value& val)
{
auto s = val.as_string();
{{#allowableValues}}{{#enumVars}}
if (s == utility::conversions::to_string_t({{{value}}})) m_value = e{{classname}}::{{classname}}_{{name}};{{/enumVars}}{{/allowableValues}}
m_value = toEnum({{#isNumeric}}val.as_number().to_int64(){{/isNumeric}}{{^isNumeric}}val.as_string(){{/isNumeric}});
return true;
}
void {{classname}}::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
if (!namePrefix.empty() && namePrefix.back() != U('.'))
{
namePrefix += utility::conversions::to_string_t(".");
namePrefix.push_back(U('.'));
}
utility::string_t s;
{{#allowableValues}}{{#enumVars}}
if (m_value == e{{classname}}::{{classname}}_{{name}}) s = utility::conversions::to_string_t({{{value}}});{{/enumVars}}{{/allowableValues}}
multipart->add(ModelBase::toHttpContent(namePrefix, s));
auto e = fromEnum(m_value);
multipart->add(ModelBase::toHttpContent(namePrefix, e));
}
bool {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
bool ok = true;
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
if (!namePrefix.empty() && namePrefix.back() != U('.'))
{
namePrefix += utility::conversions::to_string_t(".");
namePrefix.push_back(U('.'));
}
{
utility::string_t s;
ok = ModelBase::fromHttpContent(multipart->getContent(namePrefix), s);
e{{classname}} v;
{{#allowableValues}}{{#enumVars}}
if (s == utility::conversions::to_string_t({{{value}}})) v = e{{classname}}::{{classname}}_{{name}};{{/enumVars}}{{/allowableValues}}
EnumUnderlyingType e;
ok = ModelBase::fromHttpContent(multipart->getContent(namePrefix), e);
if (ok)
{
auto v = toEnum(e);
setValue(v);
}
}
return ok;
}
@ -134,7 +171,7 @@ web::json::value {{classname}}::toJson() const
{{#vars}}{{^isInherited}}
if(m_{{name}}IsSet)
{
val[utility::conversions::to_string_t("{{baseName}}")] = ModelBase::toJson(m_{{name}});
val[utility::conversions::to_string_t(U("{{baseName}}"))] = ModelBase::toJson(m_{{name}});
}{{/isInherited}}{{/vars}}
return val;
@ -147,9 +184,9 @@ bool {{classname}}::fromJson(const web::json::value& val)
ok &= this->{{{.}}}::fromJson(val);
{{/parent}}
{{#vars}}{{^isInherited}}
if(val.has_field(utility::conversions::to_string_t("{{baseName}}")))
if(val.has_field(utility::conversions::to_string_t(U("{{baseName}}"))))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("{{baseName}}"));
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("{{baseName}}")));
if(!fieldValue.is_null())
{
{{{dataType}}} refVal_{{baseName}};
@ -163,14 +200,14 @@ bool {{classname}}::fromJson(const web::json::value& val)
void {{classname}}::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U(".")))
{
namePrefix += utility::conversions::to_string_t(".");
namePrefix += utility::conversions::to_string_t(U("."));
}
{{#vars}}
if(m_{{name}}IsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("{{baseName}}")), m_{{name}}));
}
{{/vars}}
}
@ -179,16 +216,16 @@ bool {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart,
{
bool ok = true;
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U(".")))
{
namePrefix += utility::conversions::to_string_t(".");
namePrefix += utility::conversions::to_string_t(U("."));
}
{{#vars}}
if(multipart->hasContent(utility::conversions::to_string_t("{{baseName}}")))
if(multipart->hasContent(utility::conversions::to_string_t(U("{{baseName}}"))))
{
{{{dataType}}} refVal_{{baseName}};
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}")), refVal_{{baseName}} );
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("{{baseName}}"))), refVal_{{baseName}} );
{{setter}}(refVal_{{baseName}});
}
{{/vars}}

View File

@ -11,10 +11,13 @@
{{{defaultInclude}}}
#include <memory>
#include <utility>
#include <exception>
#include <corvusoft/restbed/session.hpp>
#include <corvusoft/restbed/resource.hpp>
#include <corvusoft/restbed/request.hpp>
#include <corvusoft/restbed/service.hpp>
#include <corvusoft/restbed/settings.hpp>
{{#imports}}{{{import}}}
{{/imports}}
@ -25,6 +28,22 @@ namespace {{this}} {
using namespace {{modelNamespace}};
///
/// Exception to flag problems in the handlers
///
class {{declspec}} {{classname}}Exception: public std::exception
{
public:
{{classname}}Exception(int status_code, std::string what);
int getStatus() const;
const char* what() const noexcept override;
private:
int m_status;
std::string m_what;
};
{{#operation}}
/// <summary>
/// {{summary}}
@ -35,60 +54,143 @@ using namespace {{modelNamespace}};
class {{declspec}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource: public restbed::Resource
{
public:
{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource();
{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context = "{{contextPath}}");
virtual ~{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource();
void {{httpMethod}}_method_handler(const std::shared_ptr<restbed::Session> session);
{{#vendorExtensions.x-codegen-other-methods}}
void {{httpMethod}}_method_handler(const std::shared_ptr<restbed::Session> session);
{{/vendorExtensions.x-codegen-other-methods}}
void set_handler_{{httpMethod}}(
std::function<std::pair<int, std::string>(
{{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}}
)> handler
);
protected:
//////////////////////////////////////////////////////////
// Override these to implement the server functionality //
//////////////////////////////////////////////////////////
virtual {{#returnType}}std::pair<int, {{{.}}}>{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}(
{{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});
{{#vendorExtensions.x-codegen-other-methods}}
void set_handler_{{httpMethod}}(
std::function<std::pair<int, std::string>(
{{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}}
)> handler
);
virtual {{#returnType}}std::pair<int, {{{.}}}>{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}(
{{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});
{{/vendorExtensions.x-codegen-other-methods}}
protected:
//////////////////////////////////////
// Override these for customization //
//////////////////////////////////////
virtual std::string extractBodyContent(const std::shared_ptr<restbed::Session>& session);
{{#hasPathParams}}
{{#pathParams}}
{{#isPrimitiveType}}
virtual {{{dataType}}} getPathParam_{{{paramName}}}(const std::shared_ptr<const restbed::Request>& request)
{
return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}});
}
{{/isPrimitiveType}}
{{/pathParams}}
{{/hasPathParams}}
{{#hasQueryParams}}
{{#queryParams}}
{{#isPrimitiveType}}
virtual {{{dataType}}} getQueryParam_{{{paramName}}}(const std::shared_ptr<const restbed::Request>& request)
{
return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}});
}
{{/isPrimitiveType}}
{{/queryParams}}
{{/hasQueryParams}}
{{#hasHeaderParams}}
{{#headerParams}}
{{#isPrimitiveType}}
virtual {{{dataType}}} getHeader_{{{baseName}}}(const std::shared_ptr<const restbed::Request>& request)
{
return request->get_header("{{baseName}}", {{{defaultValue}}});
}
{{/isPrimitiveType}}
{{/headerParams}}
{{/hasHeaderParams}}
{{#vendorExtensions.x-codegen-other-methods}}
{{#hasPathParams}}
{{#pathParams}}
{{#isPrimitiveType}}
virtual {{{dataType}}} getPathParam_{{{paramName}}}_x_extension(const std::shared_ptr<const restbed::Request>& request)
{
return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}});
}
{{/isPrimitiveType}}
{{/pathParams}}
{{/hasPathParams}}
{{#hasQueryParams}}
{{#queryParams}}
{{#isPrimitiveType}}
virtual {{{dataType}}} getQueryParam_{{{paramName}}}_x_extension(const std::shared_ptr<const restbed::Request>& request)
{
return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}});
}
{{/isPrimitiveType}}
{{/queryParams}}
{{/hasQueryParams}}
{{#hasHeaderParams}}
{{#headerParams}}
{{#isPrimitiveType}}
virtual {{{dataType}}} getHeader_{{{baseName}}}_x_extension(const std::shared_ptr<const restbed::Request>& request)
{
return request->get_header("{{baseName}}", {{{defaultValue}}});
}
{{/isPrimitiveType}}
{{/headerParams}}
{{/hasHeaderParams}}
{{/vendorExtensions.x-codegen-other-methods}}
virtual std::pair<int, std::string> handle{{classname}}Exception(const {{classname}}Exception& e);
virtual std::pair<int, std::string> handleStdException(const std::exception& e);
virtual std::pair<int, std::string> handleUnspecifiedException();
virtual void setResponseHeader(const std::shared_ptr<restbed::Session>& session,
const std::string& header);
virtual void returnResponse(const std::shared_ptr<restbed::Session>& session,
const int status, const std::string& result, const std::string& contentType);
virtual void defaultSessionClose(const std::shared_ptr<restbed::Session>& session,
const int status, const std::string& result);
private:
std::function<std::pair<int, std::string>(
{{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}}
)> handler_{{httpMethod}}_;
void handler_{{httpMethod}}_internal(const std::shared_ptr<restbed::Session> session);
{{#vendorExtensions.x-codegen-other-methods}}
std::function<std::pair<int, std::string>(
{{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}}
)> handler_{{httpMethod}}_;
void handler_{{httpMethod}}_internal(const std::shared_ptr<restbed::Session> session);
{{/vendorExtensions.x-codegen-other-methods}}
{{#allParams}}
{{{dataType}}} {{paramName}}{};
{{/allParams}}
};
{{/operation}}
//
// The restbed service to actually implement the REST server
//
class {{declspec}} {{classname}}: public restbed::Service
class {{declspec}} {{classname}}
{
public:
{{classname}}();
~{{classname}}();
void startService(int const& port);
void stopService();
explicit {{classname}}(std::shared_ptr<restbed::Service> const& restbedService);
virtual ~{{classname}}();
{{#operation}}
virtual void set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource);
{{/operation}}
virtual void publishDefaultResources();
virtual std::shared_ptr<restbed::Service> service();
protected:
{{#operation}}
std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource;
{{/operation}}
private:
std::shared_ptr<restbed::Service> m_service;
};

View File

@ -5,6 +5,11 @@
#include <corvusoft/restbed/string.hpp>
#include <corvusoft/restbed/settings.hpp>
#include <corvusoft/restbed/request.hpp>
#include <corvusoft/restbed/uri.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "{{classname}}.h"
@ -14,43 +19,73 @@ namespace {{this}} {
using namespace {{modelNamespace}};
{{classname}}::{{classname}}() {
}
{{classname}}::~{{classname}}() {}
void {{classname}}::startService(int const& port) {
// A typical pattern is to derive a class from {{classname}} and allocate the shared pointers for restbed::Resource objects
// and manipulate them (e.g. binding GET/POST handler functions) before this startService() gets called.
// In such a case we want to use our m_spXXX variables.
// However in case these shared pointers are nullptr, then allocate the restbed::Resources now:
{{#operation}}
if (!m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource)
m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource = std::make_shared<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource>();
this->publish(m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource);
{{/operation}}
std::shared_ptr<restbed::Settings> settings = std::make_shared<restbed::Settings>();
settings->set_port(port);
settings->set_root("{{contextPath}}");
this->start(settings);
}
void {{classname}}::stopService() {
this->stop();
}
{{#operation}}
{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource()
{{classname}}Exception::{{classname}}Exception(int status_code, std::string what)
: m_status(status_code),
m_what(what)
{
this->set_path("{{path}}");
}
int {{classname}}Exception::getStatus() const
{
return m_status;
}
const char* {{classname}}Exception::what() const noexcept
{
return m_what.c_str();
}
template<class MODEL_T>
std::shared_ptr<MODEL_T> extractJsonModelBodyParam(const std::string& bodyContent)
{
std::stringstream sstream(bodyContent);
boost::property_tree::ptree pt;
boost::property_tree::json_parser::read_json(sstream, pt);
auto model = std::make_shared<MODEL_T>(pt);
return model;
}
template<class MODEL_T>
std::vector<std::shared_ptr<MODEL_T>> extractJsonArrayBodyParam(const std::string& bodyContent)
{
std::stringstream sstream(bodyContent);
boost::property_tree::ptree pt;
boost::property_tree::json_parser::read_json(sstream, pt);
auto arrayRet = std::vector<std::shared_ptr<MODEL_T>>();
for (const auto& child: pt) {
arrayRet.emplace_back(std::make_shared<MODEL_T>(child.second));
}
return arrayRet;
}
template <class KEY_T, class VAL_T>
std::string convertMapResponse(const std::map<KEY_T, VAL_T>& map)
{
boost::property_tree::ptree pt;
for(const auto &kv: map) {
pt.push_back(boost::property_tree::ptree::value_type(
boost::lexical_cast<std::string>(kv.first),
boost::property_tree::ptree(
boost::lexical_cast<std::string>(kv.second))));
}
std::stringstream sstream;
write_json(sstream, pt);
std::string result = sstream.str();
return result;
}
{{#operation}}
{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context /* = "{{contextPath}}" */)
{
this->set_path(context + "{{path}}");
this->set_method_handler("{{httpMethod}}",
std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler, this,
std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this,
std::placeholders::_1));
{{#vendorExtensions.x-codegen-other-methods}}
this->set_method_handler("{{httpMethod}}",
std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler, this,
std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this,
std::placeholders::_1));
{{/vendorExtensions.x-codegen-other-methods}}
}
@ -59,44 +94,58 @@ void {{classname}}::stopService() {
{
}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::set_handler_{{httpMethod}}(
std::function<std::pair<int, std::string>(
{{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}}
)> handler) {
handler_{{httpMethod}}_ = std::move(handler);
std::pair<int, std::string> {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handle{{classname}}Exception(const {{classname}}Exception& e)
{
return std::make_pair<int, std::string>(e.getStatus(), e.what());
}
{{#vendorExtensions.x-codegen-other-methods}}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::set_handler_{{httpMethod}}(
std::function<std::pair<int, std::string>(
{{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}}
)> handler) {
handler_{{httpMethod}}_ = std::move(handler);
std::pair<int, std::string> {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleStdException(const std::exception& e)
{
return std::make_pair<int, std::string>(500, e.what());
}
{{/vendorExtensions.x-codegen-other-methods}}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler(const std::shared_ptr<restbed::Session> session) {
std::pair<int, std::string> {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleUnspecifiedException()
{
return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
session->set_header(header, "");
}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
session->close(status, result, { {"Connection", "close"} });
}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr<restbed::Session> session)
{
const auto request = session->get_request();
{{#hasBodyParam}}
// Body params are present, therefore we have to fetch them
int content_length = request->get_header("Content-Length", 0);
session->fetch(content_length,
[ this ]( const std::shared_ptr<restbed::Session> session, const restbed::Bytes & body )
{
std::string bodyContent = extractBodyContent(session);
const auto request = session->get_request();
std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( ));
/**
* Get body params or form params here from the file string
*/
// Get body params or form params here from the body content string
{{#allParams}}
{{#isModel}}
auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent);
{{/isModel}}
{{#isArray}}
auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent);
{{/isArray}}
{{/allParams}}
{{/hasBodyParam}}
{{#hasPathParams}}
// Getting the path params
{{#pathParams}}
{{#isPrimitiveType}}
const {{{dataType}}} {{{paramName}}} = request->get_path_parameter("{{paramName}}", {{{defaultValue}}});
const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}(request);
{{/isPrimitiveType}}
{{/pathParams}}
{{/hasPathParams}}
@ -105,7 +154,7 @@ void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMe
// Getting the query params
{{#queryParams}}
{{#isPrimitiveType}}
const {{{dataType}}} {{{paramName}}} = request->get_query_parameter("{{paramName}}", {{{defaultValue}}});
const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}(request);
{{/isPrimitiveType}}
{{/queryParams}}
{{/hasQueryParams}}
@ -114,114 +163,236 @@ void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMe
// Getting the headers
{{#headerParams}}
{{#isPrimitiveType}}
const {{{dataType}}} {{{paramName}}} = request->get_header("{{paramName}}", {{{defaultValue}}});
const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}(request);
{{/isPrimitiveType}}
{{/headerParams}}
{{/hasHeaderParams}}
// Change the value of this variable to the appropriate response before sending the response
int status_code = 200;
std::string result = "successful operation";
int status_code = 500;
{{#returnType}}
{{{.}}} resultObject = {{{defaultResponse}}};
{{/returnType}}
std::string result = "";
if (handler_{{httpMethod}}_)
{
std::tie(status_code, result) = handler_{{httpMethod}}_(
{{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}
);
try {
{{#returnType}}
std::tie(status_code, resultObject) =
{{/returnType}}
{{^returnType}}
status_code =
{{/returnType}}
handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{ / -last}}{{ / allParams}});
}
catch(const {{classname}}Exception& e) {
std::tie(status_code, result) = handle{{classname}}Exception(e);
}
catch(const std::exception& e) {
std::tie(status_code, result) = handleStdException(e);
}
catch(...) {
std::tie(status_code, result) = handleUnspecifiedException();
}
{{#responses}}
if (status_code == {{code}}) {
{{#returnType}}
{{#isModel}}
{{#isString}}
result = resultObject;
{{/isString}}
{{^isString}}
result = resultObject->toJsonString();
{{/isString}}
{{/isModel}}
{{#isMap}}
result = convertMapResponse(resultObject);
{{/isMap}}
{{/returnType}}
{{#headers}}
// Description: {{description}}
session->set_header("{{baseName}}", ""); // Change second param to your header value
// Description: {{{description}}}
setResponseHeader(session, "{{baseName}}");
{{/headers}}
session->close({{code}}, result.empty() ? "{{message}}" : std::move(result), { {"Connection", "close"} });
{{#primitiveType}}
const constexpr auto contentType = "text/plain";
{{/primitiveType}}
{{^primitiveType}}
const constexpr auto contentType = "application/json";
{{/primitiveType}}
returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType);
return;
}
{{/responses}}
{{#hasBodyParam}}
});
{{/hasBodyParam}}
defaultSessionClose(session, status_code, result);
}
{{#vendorExtensions.x-codegen-other-methods}}
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler(const std::shared_ptr<restbed::Session> session) {
// x-extension
void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr<restbed::Session> session) {
const auto request = session->get_request();
{{#hasBodyParam}}
// Body params are present, therefore we have to fetch them
int content_length = request->get_header("Content-Length", 0);
session->fetch(content_length,
[ this ]( const std::shared_ptr<restbed::Session> session, const restbed::Bytes & body )
{
std::string bodyContent = extractBodyContent(session);
const auto request = session->get_request();
std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( ));
// body params or form params here from the body content string
{{#allParams}}
{{#isModel}}
auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent);
{{/isModel}}
{{#isArray}}
auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent);
{{/isArray}}
{{^isModel}}
{{^isArray}}
auto {{paramName}} = std::make_shared<{{{baseType}}}>(bodyContent);
{{/isArray}}
{{/isModel}}
{{/allParams}}
{{/hasBodyParam}}
{{#hasPathParams}}
// Getting the path params
{{#pathParams}}
{{#isPrimitiveType}}
const {{{dataType}}} {{{paramName}}} = request->get_path_parameter("{{paramName}}", {{{defaultValue}}});
const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}_x_extension(request);
{{/isPrimitiveType}}
{{/pathParams}}
{{/hasPathParams}}
{{#hasQueryParams}}
// Getting the query params
{{#queryParams}}
{{#isPrimitiveType}}
const {{{dataType}}} {{{paramName}}} = request->get_query_parameter("{{paramName}}", {{{defaultValue}}});
const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}_x_extension(request);
{{/isPrimitiveType}}
{{/queryParams}}
{{/hasQueryParams}}
{{#hasHeaderParams}}
// Getting the headers
{{#headerParams}}
{{#isPrimitiveType}}
const {{{dataType}}} {{{paramName}}} = request->get_header("{{paramName}}", {{{defaultValue}}});
const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}_x_extension(request);
{{/isPrimitiveType}}
{{/headerParams}}
{{/hasHeaderParams}}
// Change the value of this variable to the appropriate response before sending the response
int status_code = 200;
std::string result = "successful operation";
int status_code = 500;
{{#returnType}}
{{{.}}} resultObject = {{{defaultResponse}}};
{{/returnType}}
std::string result = "";
if (handler_{{httpMethod}}_)
{
std::tie(status_code, result) = handler_{{httpMethod}}_(
{{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}
);
try {
{{#returnType}}
std::tie(status_code, resultObject) =
{{/returnType}}
{{^returnType}}
status_code =
{{/returnType}}
handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
}
catch(const {{classname}}Exception& e) {
std::tie(status_code, result) = handle{{classname}}Exception(e);
}
catch(const std::exception& e) {
std::tie(status_code, result) = handleStdException(e);
}
catch(...) {
std::tie(status_code, result) = handleUnspecifiedException();
}
{{#responses}}
if (status_code == {{code}}) {
{{#baseType}}
std::shared_ptr<{{.}}> response = NULL;
{{/baseType}}
{{#returnType}}
{{#isModel}}
{{#isString}}
result = resultObject;
{{/isString}}
{{^isString}}
result = resultObject->toJsonString();
{{/isString}}
{{/isModel}}
{{#isMap}}
result = convertMapResponse(resultObject);
{{/isMap}}
{{/returnType}}
{{#headers}}
// Description: {{description}}
session->set_header("{{baseName}}", ""); // Change second param to your header value
// Description: {{{description}}}
setResponseHeader(session, "{{baseName}}");
{{/headers}}
session->close({{code}}, result.empty() ? "{{message}}" : std::move(result), { {"Connection", "close"} });
{{#primitiveType}}
const constexpr auto contentType = "text/plain";
{{/primitiveType}}
{{^primitiveType}}
const constexpr auto contentType = "application/json";
{{/primitiveType}}
returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType);
return;
}
{{/responses}}
{{#hasBodyParam}}
});
{{/hasBodyParam}}
defaultSessionClose(session, status_code, result);
}
{{/vendorExtensions.x-codegen-other-methods}}
{{#returnType}}std::pair<int, {{{.}}}>{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}(
{{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}})
{
throw {{classname}}Exception(501, "Not implemented");
}
{{#vendorExtensions.x-codegen-other-methods}}
{{#returnType}}std::pair<int, {{{.}}}>{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}(
{{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}})
{
throw {{classname}}Exception(501, "Not implemented");
}
{{/vendorExtensions.x-codegen-other-methods}}
std::string {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
const auto request = session->get_request();
int content_length = request->get_header("Content-Length", 0);
std::string bodyContent;
session->fetch(content_length,
[&bodyContent](const std::shared_ptr<restbed::Session> session,
const restbed::Bytes &body) {
bodyContent = restbed::String::format(
"%.*s\n", (int)body.size(), body.data());
});
return bodyContent;
}
{{/operation}}
{{classname}}::{{classname}}(std::shared_ptr<restbed::Service> const& restbedService)
: m_service(restbedService)
{
}
{{classname}}::~{{classname}}() {}
{{#operation}}
void {{classname}}::set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) {
m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource = sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource;
m_service->publish(m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource);
}
{{/operation}}
void {{classname}}::publishDefaultResources() {
{{#operation}}
if (!m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) {
set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::make_shared<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource>());
}
{{/operation}}
}
std::shared_ptr<restbed::Service> {{classname}}::service() {
return m_service;
}
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}

View File

@ -13,6 +13,10 @@
{{#imports}}{{{this}}}
{{/imports}}
#include <memory>
#include <vector>
{{#hasEnums}}
#include <array>
{{/hasEnums}}
#include <boost/property_tree/ptree.hpp>
{{#modelNamespaceDeclarations}}
@ -28,8 +32,9 @@ class {{{this}}};
class {{declspec}} {{classname}} {{#interfaces}}{{#-first}}:{{/-first}}{{^-first}},{{/-first}} public {{{this}}}{{/interfaces}}
{
public:
{{classname}}();
virtual ~{{classname}}();
{{classname}}() = default;
explicit {{classname}}(boost::property_tree::ptree const& pt);
virtual ~{{classname}}() = default;
std::string toJsonString(bool prettyJson = false);
void fromJsonString(std::string const& jsonString);
@ -46,17 +51,44 @@ public:
{{{dataType}}} {{getter}}() const;
void {{setter}}({{{dataType}}} value);
{{/vars}}
protected:
//////////////////////////////////////
// Override these for customization //
//////////////////////////////////////
virtual std::string toJsonString_internal(bool prettyJson = false);
virtual void fromJsonString_internal(std::string const& jsonString);
virtual boost::property_tree::ptree toPropertyTree_internal();
virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt);
protected:
{{#vars}}
{{^isContainer}}
{{^isModel}}
{{{dataType}}} m_{{name}} = {{{defaultValue}}};
{{/isModel}}
{{#isModel}}
{{{dataType}}} m_{{name}};
{{/isModel}}
{{/isContainer}}
{{#isContainer}}
{{{dataType}}} m_{{name}};
{{/isContainer}}
{{/vars}}
{{#vars}}
{{#isEnum}}
std::vector<{{{dataType}}}> m_{{enumName}};
const std::array<std::string, {{#allowableValues}}{{#enumVars}}{{#-last}}{{-index}}{{/-last}}{{/enumVars}}{{/allowableValues}}> m_{{enumName}} = {
{{#allowableValues}}{{#enumVars}}"{{{value}}}"{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
};
{{/isEnum}}
{{/vars}}
};
std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json);
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}

View File

@ -4,6 +4,7 @@
#include "{{classname}}.h"
#include <string>
#include <vector>
#include <sstream>
#include <stdexcept>
{{#hasEnums}}
@ -20,43 +21,39 @@ using boost::property_tree::write_json;
namespace {{this}} {
{{/modelNamespaceDeclarations}}
{{classname}}::{{classname}}()
{{classname}}::{{classname}}(boost::property_tree::ptree const& pt)
{
{{#vars}}
{{^isContainer}}
{{#isPrimitiveType}}
m_{{name}} = {{{defaultValue}}};
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{#isString}}
m_{{name}} = {{{defaultValue}}};
{{/isString}}
{{#isDate}}
m_{{name}} = {{{defaultValue}}};
{{/isDate}}
{{#isDateTime}}
m_{{name}} = {{{defaultValue}}};
{{/isDateTime}}
{{#isEnum}}
m_{{enumName}} = { {{#allowableValues}}{{#enumVars}}{{^-first}}, {{/-first}}{{{value}}}{{/enumVars}}{{/allowableValues}} };
{{/isEnum}}
{{/isPrimitiveType}}
{{/isContainer}}
{{/vars}}
fromPropertyTree(pt);
}
{{classname}}::~{{classname}}()
std::string {{classname}}::toJsonString(bool prettyJson /* = false */)
{
return toJsonString_internal(prettyJson);
}
std::string {{classname}}::toJsonString(bool prettyJson)
void {{classname}}::fromJsonString(std::string const& jsonString)
{
fromJsonString_internal(jsonString);
}
boost::property_tree::ptree {{classname}}::toPropertyTree()
{
return toPropertyTree_internal();
}
void {{classname}}::fromPropertyTree(boost::property_tree::ptree const& pt)
{
fromPropertyTree_internal(pt);
}
std::string {{classname}}::toJsonString_internal(bool prettyJson)
{
std::stringstream ss;
write_json(ss, this->toPropertyTree(), prettyJson);
return ss.str();
}
void {{classname}}::fromJsonString(std::string const& jsonString)
void {{classname}}::fromJsonString_internal(std::string const& jsonString)
{
std::stringstream ss(jsonString);
ptree pt;
@ -64,7 +61,7 @@ void {{classname}}::fromJsonString(std::string const& jsonString)
this->fromPropertyTree(pt);
}
ptree {{classname}}::toPropertyTree()
ptree {{classname}}::toPropertyTree_internal()
{
ptree pt;
ptree tmp_node;
@ -91,34 +88,29 @@ ptree {{classname}}::toPropertyTree()
{{/isPrimitiveType}}
{{/isContainer}}
{{#isContainer}}
{{^isModelContainer}}
// generate tree for {{name}}
if (!m_{{name}}.empty()) {
for (const auto &childEntry : m_{{name}}) {
{{#items}}
{{#isModel}}
tmp_node.push_back(std::make_pair("", childEntry->toPropertyTree()));
{{/isModel}}
{{^isModel}}
ptree {{name}}_node;
{{name}}_node.put("", childEntry);
tmp_node.push_back(std::make_pair("", {{name}}_node));
{{/isModel}}
{{/items}}
}
pt.add_child("{{baseName}}", tmp_node);
tmp_node.clear();
}
{{/isModelContainer}}
{{#isModelContainer}}
// generate tree for vector of pointers of {{name}}
if (!m_{{name}}.empty()) {
for (const auto &childEntry : m_{{name}}) {
tmp_node.push_back(std::make_pair("", childEntry->toPropertyTree()));
}
pt.add_child("{{baseName}}", tmp_node);
tmp_node.clear();
}
{{/isModelContainer}}
{{/isContainer}}
{{/vars}}
return pt;
}
void {{classname}}::fromPropertyTree(ptree const &pt)
void {{classname}}::fromPropertyTree_internal(ptree const &pt)
{
ptree tmp_node;
{{#vars}}
@ -155,7 +147,35 @@ void {{classname}}::fromPropertyTree(ptree const &pt)
if (pt.get_child_optional("{{baseName}}")) {
for (const auto &childTree : pt.get_child("{{baseName}}")) {
{{#mostInnerItems}}
m_{{name}}.emplace_back({{#isNumeric}}{{^isFloat}}{{^isLong}}{{^isInteger}}std::stod{{/isInteger}}{{/isLong}}{{/isFloat}}{{#isDouble}}std::stod{{/isDouble}}{{#isFloat}}std::stof{{/isFloat}}{{#isInteger}}std::stoi{{/isInteger}}{{#isLong}}std::stol{{/isLong}}({{/isNumeric}}childTree.second.data()){{#isNumeric}}){{/isNumeric}};
{{{dataType}}} val =
{{#isNumeric}}
{{^isFloat}}
{{^isLong}}
{{^isInteger}}
std::stod(childTree.second.data());
{{/isInteger}}
{{/isLong}}
{{/isFloat}}
{{#isDouble}}
std::stod(childTree.second.data());
{{/isDouble}}
{{#isFloat}}
std::stof(childTree.second.data());
{{/isFloat}}
{{#isInteger}}
std::stoi(childTree.second.data());
{{/isInteger}}
{{#isLong}}
std::stol(childTree.second.data());
{{/isLong}}
{{/isNumeric}}
{{#isString}}
childTree.second.data();
{{/isString}}
{{#isModel}}
std::make_shared<{{baseType}}>(childTree.second);
{{/isModel}}
m_{{name}}.emplace_back(std::move(val));
{{/mostInnerItems}}
}
}
@ -180,6 +200,7 @@ void {{classname}}::fromPropertyTree(ptree const &pt)
{
return m_{{name}};
}
void {{classname}}::{{setter}}({{{dataType}}} value)
{
{{#isEnum}}if (std::find(m_{{enumName}}.begin(), m_{{enumName}}.end(), value) != m_{{enumName}}.end()) {
@ -190,6 +211,20 @@ void {{classname}}::{{setter}}({{{dataType}}} value)
}
{{/vars}}
std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json)
{
std::stringstream sstream(json);
boost::property_tree::ptree pt;
boost::property_tree::json_parser::read_json(sstream,pt);
auto vec = std::vector<{{{classname}}}>();
for (const auto& child: pt) {
vec.emplace_back({{{classname}}}(child.second));
}
return vec;
}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}

View File

@ -1,138 +0,0 @@
# Call an API with given options.
#
# @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers.
def call_api(http_method, path, opts = {} of Symbol => String)
ssl_options = {
:ca_file => @config.ssl_ca_file,
:verify => @config.ssl_verify,
:verify_mode => @config.ssl_verify_mode,
:client_cert => @config.ssl_client_cert,
:client_key => @config.ssl_client_key
}
connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn|
conn.basic_auth(config.username, config.password)
if opts[:header_params]["Content-Type"] == "multipart/form-data"
conn.request :multipart
conn.request :url_encoded
end
conn.adapter(Faraday.default_adapter)
end
begin
response = connection.public_send(http_method.to_sym.downcase) do |req|
build_request(http_method, path, req, opts)
end
if @config.debugging
Log.debug {"HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"}
end
unless response.success?
if response.status == 0
# Errors from libcurl will be made visible here
fail ApiError.new(code: 0,
message: response.return_message)
else
fail ApiError.new(code: response.status,
response_headers: response.headers,
response_body: response.body),
response.reason_phrase
end
end
rescue Faraday::TimeoutError
fail ApiError.new("Connection timed out")
end
if opts[:return_type]
data = deserialize(response, opts[:return_type])
else
data = nil
end
return data, response.status, response.headers
end
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Typhoeus::Request] A Typhoeus Request
def build_request(http_method, path, request, opts = {} of Symbol => String)
url = build_request_url(path, opts)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {} of Symbole => String)
query_params = opts[:query_params] || {} of Symbol => String
form_params = opts[:form_params] || {} of Symbol => String
update_params_for_auth! header_params, query_params, opts[:auth_names]
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:params_encoding => @config.params_encoding,
:timeout => @config.timeout,
:verbose => @config.debugging
}
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging
Log.debug {"HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"}
end
end
request.headers = header_params
request.body = req_body
request.url url
request.params = query_params
download_file(request) if opts[:return_type] == "File"
request
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params["Content-Type"] == "application/x-www-form-urlencoded"
data = URI.encode_www_form(form_params)
elsif header_params["Content-Type"] == "multipart/form-data"
data = {} of Symbol => String
form_params.each do |key, value|
case value
when ::File, ::Tempfile
# TODO hardcode to application/octet-stream, need better way to detect content type
data[key] = Faraday::UploadIO.new(value.path, "application/octet-stream", value.path)
when ::Array, nil
# let Faraday handle Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
def download_file(request)
@stream = []
# handle streaming Responses
request.options.on_data = Proc.new do |chunk, overall_received_bytes|
@stream << chunk
end
end

View File

@ -162,6 +162,7 @@
{{^isReadOnly}}
{{^required}}
{{#defaultValue}}
{{^conditionalSerialization}}
{{^vendorExtensions.x-csharp-value-type}}
// use default value if no "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" provided
this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? {{{defaultValue}}};
@ -169,6 +170,7 @@
{{#vendorExtensions.x-csharp-value-type}}
this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}};
{{/vendorExtensions.x-csharp-value-type}}
{{/conditionalSerialization}}
{{/defaultValue}}
{{^defaultValue}}
{{^conditionalSerialization}}

View File

@ -105,7 +105,13 @@ class _${{classname}}Serializer implements StructuredSerializer<{{classname}}> {
result.{{{name}}}.replace(valueDes);
{{/isContainer}}
{{#isModel}}
{{#isPrimitiveType}}
{{! These are models that have nee manually marked as primitve via generator param. }}
result.{{{name}}} = valueDes;
{{/isPrimitiveType}}
{{^isPrimitiveType}}
result.{{{name}}}.replace(valueDes);
{{/isPrimitiveType}}
{{/isModel}}
{{^isContainer}}
{{^isModel}}

View File

@ -197,33 +197,7 @@ class {{{classname}}} {
{{/isMap}}
{{^isMap}}
return await apiClient.deserializeAsync(await _decodeBodyBytes(response), '{{{returnType}}}',) as {{{returnType}}};
{{/isMap}}{{/isArray}}{{/native_serialization}}{{#json_serializable}}
{{#isArray}}
{{#uniqueItems}}
return (json.decode(response.body) as List)
.map((i) => {{{returnBaseType}}}.fromJson(i))
.toSet();
{{/uniqueItems}}
{{^uniqueItems}}
return (json.decode(response.body) as List)
.map((i) => {{{returnBaseType}}}.fromJson(i))
.toList();
{{/uniqueItems}}
{{/isArray}}
{{^isArray}}
{{#isMap}}
return {{{returnType}}}.from(json.decode(response.body));
{{/isMap}}
{{^isMap}}
{{#returnTypeIsPrimitive}}
return response.body as {{{returnBaseType}}};
{{/returnTypeIsPrimitive}}
{{^returnTypeIsPrimitive}}
return {{{returnType}}}.fromJson(json.decode(response.body));
{{/returnTypeIsPrimitive}}
{{/isMap}}
{{/isArray}}
{{/json_serializable}}
{{/isMap}}{{/isArray}}{{/native_serialization}}
}
return Future<{{{returnType}}}>.value();
{{/returnType}}

View File

@ -208,7 +208,6 @@ class ApiClient {
case '{{{classname}}}':
{{#isEnum}}
{{#native_serialization}}return {{{classname}}}TypeTransformer().decode(value);{{/native_serialization}}
{{#json_serializable}} return _$enumDecode(_${{{classname}}}EnumMap, value);{{/json_serializable}}
{{/isEnum}}
{{^isEnum}}
return {{{classname}}}.fromJson(value);

View File

@ -54,7 +54,7 @@ String parameterToString(dynamic value) {
{{#model}}
{{#isEnum}}
if (value is {{{classname}}}) {
{{#native_serialization}} return {{{classname}}}TypeTransformer().encode(value).toString();{{/native_serialization}}{{#json_serializable}} return value.toString();{{/json_serializable}}
{{#native_serialization}} return {{{classname}}}TypeTransformer().encode(value).toString();{{/native_serialization}}
}
{{/isEnum}}
{{/model}}

View File

@ -7,9 +7,6 @@ import 'dart:io';
import 'package:http/http.dart';
import 'package:intl/intl.dart';
{{#json_serializable}}
import 'package:json_annotation/json_annotation.dart';
{{/json_serializable}}
import 'package:meta/meta.dart';
part 'api_client.dart';
@ -26,9 +23,6 @@ part 'auth/http_bearer_auth.dart';
{{#models}}{{#model}}part 'model/{{{classFilename}}}.dart';
{{/model}}{{/models}}
{{#json_serializable}}
part 'api.g.dart';
{{/json_serializable}}
const _delimiters = {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'};
const _dateEpochMarker = 'epoch';
final _dateFormatter = DateFormat('yyyy-MM-dd');

View File

@ -1,18 +0,0 @@
targets:
$default:
builders:
json_serializable:
options:
# Options configure how source code is generated for every
# `@JsonSerializable`-annotated class in the package.
#
# The default value for each is listed.
any_map: false
checked: true
create_factory: true
create_to_json: true
disallow_unrecognized_keys: true
explicit_to_json: true
field_rename: none
ignore_unannotated: false
include_if_null: false

View File

@ -6,17 +6,11 @@
{{#native_serialization}}
{{>serialization/native/native_enum}}
{{/native_serialization}}
{{#json_serializable}}
{{>serialization/json_serializable/json_serializable_enum}}
{{/json_serializable}}
{{/isEnum}}
{{^isEnum}}
{{#native_serialization}}
{{>serialization/native/native_class}}
{{/native_serialization}}
{{#json_serializable}}
{{>serialization/json_serializable/json_serializable_class}}
{{/json_serializable}}
{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -12,10 +12,5 @@ dependencies:
http: '>=0.13.0 <0.14.0'
intl: '^0.17.0'
meta: '^1.1.8'
{{#json_serializable}}
json_annotation: '^3.1.1'{{/json_serializable}}
dev_dependencies:
test: '>=1.16.0 <1.18.0'
{{#json_serializable}}
build_runner: '^1.10.9'
json_serializable: '^3.5.1'{{/json_serializable}}

View File

@ -1,67 +0,0 @@
@JsonSerializable(
checked: true,
createToJson: true,
disallowUnrecognizedKeys: true,
explicitToJson: true,
)
class {{{classname}}} {
{{>dart_constructor}}
{{#vars}}
{{#description}}
/// {{{.}}}
{{/description}}
{{^isEnum}}
{{#minimum}}
// minimum: {{{.}}}
{{/minimum}}
{{#maximum}}
// maximum: {{{.}}}
{{/maximum}}
{{/isEnum}}
{{^isBinary}}
@JsonKey(
{{#defaultValue}}defaultValue: {{{.}}},{{/defaultValue}}{{^defaultValue}}nullable: {{isNullable}},{{/defaultValue}}
name: r'{{{baseName}}}',
required: {{#required}}true{{/required}}{{^required}}false{{/required}},
)
{{/isBinary}}
{{#isBinary}}
@JsonKey(ignore: true)
{{/isBinary}}
{{{datatypeWithEnum}}} {{{name}}};
{{/vars}}
@override
bool operator ==(Object other) => identical(this, other) || other is {{{classname}}} &&
{{#vars}}
other.{{{name}}} == {{{name}}}{{^-last}} &&{{/-last}}{{#-last}};{{/-last}}
{{/vars}}
@override
int get hashCode =>
{{#vars}}
({{{name}}} == null ? 0 : {{{name}}}.hashCode){{^-last}} +{{/-last}}{{#-last}};{{/-last}}
{{/vars}}
factory {{{classname}}}.fromJson(Map<String, dynamic> json) => _${{{classname}}}FromJson(json);
Map<String, dynamic> toJson() => _${{{classname}}}ToJson(this);
@override
String toString() => toJson().toString();
}
{{#vars}}
{{#isEnum}}
{{^isContainer}}
{{>serialization/json_serializable/json_serializable_enum_inline}}
{{/isContainer}}
{{#isContainer}}
{{#mostInnerItems}}
{{>serialization/json_serializable/json_serializable_enum_inline}}
{{/mostInnerItems}}
{{/isContainer}}
{{/isEnum}}
{{/vars}}

View File

@ -1,7 +0,0 @@
enum {{{classname}}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}},
{{/enumVars}}
{{/allowableValues}}
}

View File

@ -1,8 +0,0 @@
{{#description}}/// {{{.}}}{{/description}}
enum {{{enumName}}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}},
{{/enumVars}}
{{/allowableValues}}
}

View File

@ -4,11 +4,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
{{#eurekaUri}}
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
{{/eurekaUri}}
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
@ -22,8 +20,6 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
{{#eurekaUri}}
@EnableEurekaClient
{{/eurekaUri}}
@EnableCircuitBreaker
@EnableHystrixDashboard
public class {{serviceName}}Application {
private static final Logger LOGGER = LoggerFactory.getLogger({{serviceName}}Application.class);

View File

@ -113,18 +113,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<!--<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix-stream</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>

View File

@ -38,10 +38,6 @@ info:
description: Microservice developed by PKMST
version: {{artifactVersion}}
health:
hystrix:
enabled: true
security:
basic:
enabled: false

View File

@ -38,13 +38,10 @@ info:
description: Microservice developed by PKMST
version: {{artifactVersion}}
health:
hystrix:
enabled: true
security:
basic:
enabled: false
# provide rabbitmq configuration
spring:
rabbitmq:

View File

@ -7,7 +7,7 @@ class HttpBasicAuth : Authentication {
var username: String? = null
var password: String? = null
@InternalAPI
@OptIn(InternalAPI::class)
override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
if (username == null && password == null) return
val str = (username ?: "") + ":" + (password ?: "")

View File

@ -19,7 +19,7 @@ This server has been generated with [Laminas (Zend) PSR-7 implementation](https:
## Requirements
* Web server with URL rewriting
* PHP 7.2 or newer
* PHP 7.3 or newer
This package contains `.htaccess` for Apache configuration.
If you use another server(Nginx, HHVM, IIS, lighttpd) check out [Web Servers](https://www.slimframework.com/docs/v3/start/web-servers.html) doc.

View File

@ -8,7 +8,7 @@
}
],
"require": {
"php": "^7.2",
"php": "^7.3 || ^8.0",
"slim/slim": "^4.5.0",
"dyorg/slim-token-authentication": "dev-slim4",
"ybelenko/openapi-data-mocker": "^1.0",

View File

@ -2,7 +2,7 @@
{{#appName}}
* {{{.}}}
{{/appName}}
* PHP version 7.2
* PHP version 7.3
*
* @package {{invokerPackage}}
* @author OpenAPI Generator team

View File

@ -1,15 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/4.8/phpunit.xsd"
bootstrap="./vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
beStrictAboutTestsThatDoNotTestAnything="false"
stopOnFailure="false"
>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd" bootstrap="./vendor/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" beStrictAboutTestsThatDoNotTestAnything="false" stopOnFailure="false">
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">{{apiSrcPath}}</directory>
<file>./{{srcBasePath}}/BaseModel.php</file>
<directory suffix=".php">{{modelSrcPath}}</directory>
</include>
</coverage>
<testsuites>
<testsuite name="Apis">
<directory>{{apiTestPath}}</directory>
@ -19,13 +16,6 @@
<directory>{{modelTestPath}}</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">{{apiSrcPath}}</directory>
<file>./{{srcBasePath}}/BaseModel.php</file>
<directory suffix=".php">{{modelSrcPath}}</directory>
</whitelist>
</filter>
<php>
<ini name="error_reporting" value="E_ALL"/>
</php>

View File

@ -296,6 +296,9 @@ class ObjectSerializer
if ($class === 'object') {
settype($data, 'array');
return $data;
} else if ($class === 'mixed') {
settype($data, gettype($data));
return $data;
}
if ($class === '\DateTime') {

View File

@ -21,6 +21,7 @@ namespace {{apiPackage}};
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
@ -197,6 +198,13 @@ use {{invokerPackage}}\ObjectSerializer;
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? (string) $e->getResponse()->getBody() : null
);
} catch (ConnectException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
(int) $e->getCode(),
null,
null
);
}
$statusCode = $response->getStatusCode();
@ -552,7 +560,7 @@ use {{invokerPackage}}\ObjectSerializer;
$formParams['{{baseName}}'] = [];
$paramFiles = is_array(${{paramName}}) ? ${{paramName}} : [${{paramName}}];
foreach ($paramFiles as $paramFile) {
$formParams['{{baseName}}'][] = \GuzzleHttp\Psr7\try_fopen(
$formParams['{{baseName}}'][] = \GuzzleHttp\Psr7\Utils::tryFopen(
ObjectSerializer::toFormValue($paramFile),
'rb'
);
@ -607,7 +615,7 @@ use {{invokerPackage}}\ObjectSerializer;
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
$httpBody = \GuzzleHttp\Psr7\Query::build($formParams);
}
}
@ -660,7 +668,7 @@ use {{invokerPackage}}\ObjectSerializer;
$operationHost = $operationHosts[$this->hostIndex];
{{/servers.0}}
$query = \GuzzleHttp\Psr7\build_query($queryParams);
$query = \GuzzleHttp\Psr7\Query::build($queryParams);
return new Request(
'{{httpMethod}}',
{{^servers.0}}$this->config->getHost(){{/servers.0}}{{#servers.0}}$operationHost{{/servers.0}} . $resourcePath . ($query ? "?{$query}" : ''),

View File

@ -28,7 +28,8 @@
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
"guzzlehttp/guzzle": "^6.2"
"guzzlehttp/guzzle": "^7.3",
"guzzlehttp/psr7": "^2.0"
},
"require-dev": {
"phpunit/phpunit": "^8.0 || ^9.0",

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