Compare commits

...

38 Commits

Author SHA1 Message Date
William Cheng
6fdc277f18 remove set e 2025-03-13 20:24:23 +08:00
dependabot[bot]
a3fb8f59f8 Bump dorny/test-reporter from 1 to 2 (#20862)
Bumps [dorny/test-reporter](https://github.com/dorny/test-reporter) from 1 to 2.
- [Release notes](https://github.com/dorny/test-reporter/releases)
- [Changelog](https://github.com/dorny/test-reporter/blob/main/CHANGELOG.md)
- [Commits](https://github.com/dorny/test-reporter/compare/v1...v2)

---
updated-dependencies:
- dependency-name: dorny/test-reporter
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-13 18:47:34 +08:00
Pietro Bongiovanni
5c51ee49a2 [Rust Server] Bump up env_logger to 0.11 (#20865)
* Bump up env_logger to 0.11

* regenerate examples

* regenerate examples
2025-03-13 18:45:50 +08:00
William Cheng
3ab495a0aa Fix operationId mapping (#20846)
* fix operationId mapping

* add tests

* minor change
2025-03-12 20:28:18 +08:00
William Cheng
e40f9e3801 update C# samples 2025-03-12 18:18:16 +08:00
Jacob Ilsø
7f40ce0dd8 Use interfaces for Polly retry policies (#20821)
This enables use of ResiliencePipelineBuilder which returns the
interface when calling AsSyncPolicy / AsAsyncPolicy
2025-03-12 16:49:03 +08:00
Josh Keighley
7d9e1ecc22 Bump feign version to 13.5 from 10.12. (#20849) 2025-03-12 16:35:36 +08:00
Daniel Schreiber
8ead4b6e3f [typescript-angular] fix: correctly serialize query params objects (#20850)
fixes #20799
2025-03-12 09:22:49 +01:00
William Cheng
0e34d39833 add tests, option for useVirtualHooks (csharp) (#20837) 2025-03-11 00:02:30 +08:00
mahmoud_ zeyada
21be5f5abc fix(typescript-nestjs): handle query params serialization properly (#20755)
* fix(typescript-nestjs): handle query params serialization properly

* fix(typescript-nestjs): updated the samples for param serialization fix
2025-03-10 16:07:21 +01:00
Jarangutan
4ad76cc86c [go-server] Moved helper code from router and updated logger for chi (#20823)
* [go-server] Moved helper code from router and updated logger

* [go-server] fixed imports for mux and chi

* [go-server] fix go-api-server sample test
2025-03-09 15:47:11 +08:00
Sam Ward
e8ae249cad [csharp] Add useVirtualForHooks option (#20705) 2025-03-08 17:30:58 +08:00
Brian Ferri
cde0f551fc [PHP-NEXTGEN] make allowable values enum getter static (#20820)
* [PHP-NEXTGEN] make allowable values enum getter static

* [PHP-NEXTGEN] make allowable values enum getter static
2025-03-08 16:39:48 +08:00
William Cheng
7f64246b20 use nim own petstore test spec (#20819) 2025-03-07 15:35:50 +08:00
lucy66hw
b528e4a7a7 [protobuf-schema] Support oneOf and AnyOf (#20798)
* handle primitive oneof

handle anyof

* Add oneof and anyof test in petstore
2025-03-07 15:10:07 +08:00
martin-mfg
74e49ac1d2 use java.io.Serializable (#20815) 2025-03-07 00:17:06 +08:00
Daniel Schreiber
ce0c0dcab0 [typescript-angular] fix: update basePath initialization to use template variable (#20816)
fixes #20760
2025-03-06 17:05:20 +01:00
David
ba2e50519d improve documentation for RESOLVE_INLINE_ENUMS (#20812)
related to #20790
2025-03-06 18:28:45 +08:00
jpfinne
ffa196e6a9 Add x-implements for java enums (#20778) 2025-03-06 01:59:55 +08:00
Tyler Mairose
36b72052e6 Add tag and method filters during generation (#20801)
* Add Filter by tag and method under OpenAPINormalizer

* Update message for invalid filters

* Update customization documentation with new filters

* Add comment for new code block
2025-03-06 01:49:47 +08:00
Julien Debon
123119c076 Add the dependencies in the generated Opam file (#20805) 2025-03-05 19:38:41 +08:00
William Cheng
890c758fd8 Add github workflow for OCaml samples (#20802)
* add github workflow for ocaml sample

* trigger build

* test with 5

* install dune

* install yojson

* install others

* install

* add name

* trigger build failure

* Revert "trigger build failure"

This reverts commit be35b26a83.

* test with 5

* pin versions
2025-03-05 18:07:44 +08:00
sabra
f2bbb9e0a2 [java] generateClientAsBean for restclient and webclient (#20754)
* [java] generateClientAsBean for restclient and webclient

Added possibility to generate restclient and webclient as a @Component in the same fashion as resttemplate.

Fix #17885
Fix #19229

* - Samples
2025-03-05 17:50:24 +08:00
Jakob Warkotsch
efc53f5d47 [JavaScript] Avoid undefined headers with skipDefaultUserAgent enabled (#20792)
Prior to this commit, a JS client generated with skipDefaultUserAgent
enabled results in a src/ApiClient.js file that doesn't define
this.defaultHeaders. This breaks because this.defaultHeaders is later
directly passed to a superagent request which expects an object and not
undefined.

Fixes #20791.
2025-03-05 17:36:07 +08:00
Julien Debon
0f13dfedb9 [OCaml] Fix default optional list (#20789)
* Cleanup the existing model template

* `{{^isContainer}}foobar{{/isContainer}}{{^isContainer}}` is equivalent to `{{^isContainer}}foobar`
* Add indentations to make it easier to read the template. The generated code is
uglier, but it is ok since users are encouraged to reformat anyway

* Add a default value for non-required lists

Closes https://github.com/OpenAPITools/openapi-generator/issues/20777
2025-03-05 01:41:21 +08:00
lucy66hw
c96d3088c5 [protobuf-schema] Use snake_case for protobuf fields, UPPER_SNAKE_CASE for enums. (#20696)
* protobuf enum prefix use upper underscore

Add json name parameters and change parameter field name to snake case

* rerun generate-samples.sh

* Add CI test

* rebase master

---------

Co-authored-by: xil <xil@uber.com>
2025-03-04 17:18:07 +08:00
Julien Debon
90de8dcd75 [OCaml] Add key to each model field (#20766)
* Add key to each model field

Add a `[@key "someField"]` annotation to each model field, to avoid mismatches when the JSON field is not in snake_case.

Closes https://github.com/OpenAPITools/openapi-generator/issues/20765

* update ocaml samples

---------

Co-authored-by: William Cheng <wing328hk@gmail.com>
2025-03-04 16:49:27 +08:00
martin-mfg
a018c10c70 fix Maven plugin tests (#20782)
* fix maven test

* fix another maven test
2025-03-04 10:42:44 +08:00
Ron Reynolds
2cff152e2a adding Intellij style xml and applied to all java code (#20734)
* added intellij-codestyle.xml and sample of it being applied to some java code-gen classes

* code-format changes ONLY

* few more format changes since last merge with master

* applied code-style to all java one last time
2025-03-04 01:44:48 +08:00
William Cheng
3ad5303f99 update samples 2025-03-03 19:29:07 +08:00
martin-mfg
2b8d496c80 [#19921] Add RFC 3339 compatible Jackson module for java.time types, regenerate samples (#20700)
Co-authored-by: Christian Beikov <christian.beikov@gmail.com>
2025-03-03 17:42:18 +08:00
Ron Reynolds
5cef0803b8 Java client enhanced Configuration with ApiClient Supplier (#20738)
* enhanced Configuration.mustache (thread-safe, lazy-eval, plugable factory

* removed comment in Configuration.mustache

* fresh samples
2025-03-03 13:52:10 +08:00
sandwoodK
e0b6b2bbc7 Fix nim code generation (#20752)
Same variable name declared multiple times in the same scope.
=> nim generated code does not compile.
2025-03-03 13:50:19 +08:00
Iurii Ignatko
af536f6205 Finalize [this-escape] warnings fixes in apache-httpclient (#20774) 2025-03-03 13:01:08 +08:00
Han van Venrooij
ecdd8b5442 Upgrade plexus-build-api (#20759) 2025-03-03 10:33:18 +08:00
Simone Dalcastagné
70df1170cc fix: authorization values in Java modules (#20644) 2025-03-02 23:39:37 +08:00
Ross Sullivan
85ab65c4ca Fixed allOf with only one model (#20716) 2025-03-02 23:33:00 +08:00
William Cheng
a79aad8420 Prepare 7.13.0 (#20758)
* Revert "v7.12.0 release"

This reverts commit 073723cb4d.

* set version to v7.13.0-SNAPSHOT

* update samples

* update doc
2025-02-28 13:48:36 +08:00
7948 changed files with 31366 additions and 15799 deletions

View File

@@ -11,7 +11,7 @@ jobs:
report:
runs-on: ubuntu-latest
steps:
- uses: dorny/test-reporter@v1
- uses: dorny/test-reporter@v2
with:
artifact: surefire-test-results
name: JUnit Test results

View File

@@ -16,6 +16,7 @@ jobs:
matrix:
sample:
- samples/client/petstore/csharp/restsharp/net8/ParameterMappings/
- samples/client/petstore/csharp/restsharp/net8/useVirtualForHooks/
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4.3.0

31
.github/workflows/samples-ocaml.yaml vendored Normal file
View File

@@ -0,0 +1,31 @@
name: Samples OCaml
on:
push:
paths:
- 'samples/client/petstore/ocaml/**'
pull_request:
paths:
- 'samples/client/petstore/ocaml/**'
jobs:
build:
name: Build OCaml
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
sample:
- 'samples/client/petstore/ocaml/'
steps:
- uses: actions/checkout@v4
- name: Set-up OCaml
uses: ocaml/setup-ocaml@v3
with:
ocaml-compiler: 5
- name: Install
run: opam install . --deps-only --with-test
working-directory: ${{ matrix.sample }}
- name: Build
run: opam exec -- dune build
working-directory: ${{ matrix.sample }}

38
.github/workflows/samples-protobuf.yaml vendored Normal file
View File

@@ -0,0 +1,38 @@
name: Samples Protobuf
on:
push:
paths:
- .github/workflows/samples-protobuf.yaml
- samples/config/petstore/protobuf-schema/**
- samples/config/petstore/protobuf-schema-config/**
pull_request:
paths:
- .github/workflows/samples-protobuf.yaml
- samples/config/petstore/protobuf-schema/**
- samples/config/petstore/protobuf-schema-config/**
jobs:
build:
name: Build Protobuf Client
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
sample:
- 'samples/config/petstore/protobuf-schema/'
- 'samples/config/petstore/protobuf-schema-config/'
steps:
- uses: actions/checkout@v4
- name: Install Protocol Buffers Compiler
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
- name: Generate Protobuf Schema
working-directory: ${{ matrix.sample }}
run: |
mkdir out
protoc --proto_path=. --cpp_out=out models/*.proto services/*.proto
- name: Verify Generated Files
working-directory: ${{ matrix.sample }}
run: |
ls -l out/models
ls -l out/services

View File

@@ -68,7 +68,6 @@ elif [ "$NODE_INDEX" = "3" ]; then
echo "Running node $NODE_INDEX ... "
# Install node@stable (for angular 6)
set +e
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
export NVM_DIR="/opt/circleci/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

View File

@@ -15,7 +15,7 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`7.12.0`):
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`7.13.0`):
[![Build Status](https://api.travis-ci.com/OpenAPITools/openapi-generator.svg?branch=master&status=passed)](https://app.travis-ci.com/github/OpenAPITools/openapi-generator/builds)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator)
@@ -131,8 +131,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
| OpenAPI Generator Version | Release Date | Notes |
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- |
| 7.12.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.12.0-SNAPSHOT/) | 17.02.2024 | Minor release with breaking changes (with fallback) |
| [7.11.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v7.11.0) (latest stable release) | 20.01.2024 | Minor release with breaking changes (with fallback) |
| 7.13.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.13.0-SNAPSHOT/) | 02.04.2025 | Minor release with breaking changes (with fallback) |
| [7.12.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v7.12.0) (latest stable release) | 28.02.2025 | Minor release with breaking changes (with fallback) |
| [6.6.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v6.6.0) | 11.05.2023 | Minor release with breaking changes (with fallback) |
| [5.4.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.4.0) | 31.01.2022 | Minor release with breaking changes (with fallback) |
| [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) |
@@ -195,16 +195,16 @@ See the different versions of the [openapi-generator-cli](https://search.maven.o
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 11 runtime at a minimum):
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.11.0/openapi-generator-cli-7.11.0.jar`
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar`
For **Mac/Linux** users:
```sh
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.11.0/openapi-generator-cli-7.11.0.jar -O openapi-generator-cli.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar -O openapi-generator-cli.jar
```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
```
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.11.0/openapi-generator-cli-7.11.0.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@@ -439,7 +439,7 @@ openapi-generator-cli version
To use a specific version of "openapi-generator-cli"
```sh
openapi-generator-cli version-manager set 7.11.0
openapi-generator-cli version-manager set 7.12.0
```
Or install it as dev-dependency:
@@ -463,7 +463,7 @@ pip install openapi-generator-cli
To install a specific version
```
pip install openapi-generator-cli==7.11.0
pip install openapi-generator-cli==7.12.0
```
You can also install with [jdk4py](https://github.com/activeviam/jdk4py) instead of java binary. (python>=3.10 is required)
@@ -489,7 +489,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
(if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`)
<!-- RELEASE_VERSION -->
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.11.0/openapi-generator-cli-7.11.0.jar)
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.12.0/openapi-generator-cli-7.12.0.jar)
<!-- /RELEASE_VERSION -->
To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate`

View File

@@ -0,0 +1,10 @@
# for .net standard
generatorName: csharp
library: restsharp
outputDir: samples/client/petstore/csharp/restsharp/net8/useVirtualForHooks
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-addpet-only.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp
additionalProperties:
packageGuid: '{D0A67E81-4061-48EB-B4B8-C73BDF8B2D95}'
targetFramework: net8.0
useVirtualForHooks: true

View File

@@ -1,6 +1,6 @@
generatorName: nim
outputDir: samples/client/petstore/nim
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/nim/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/nim-client
additionalProperties:
packageName: petstore

View File

@@ -0,0 +1,9 @@
generatorName: protobuf-schema
outputDir: samples/config/petstore/protobuf-schema-config
inputSpec: modules/openapi-generator/src/test/resources/3_0/protobuf/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/protobuf-schema
additionalProperties:
packageName: petstore
addJsonNameAnnotation: true
numberedFieldNumberList: true
startEnumsWithUnspecified: true

View File

@@ -504,7 +504,7 @@ Another useful option is `inlineSchemaOptions`, which allows you to customize ho
- `MAP_ITEM_SUFFIX` set the map item suffix
- `SKIP_SCHEMA_REUSE=true` is a special value to skip reusing inline schemas during refactoring
- `REFACTOR_ALLOF_INLINE_SCHEMAS=true` will restore the 6.x (or below) behaviour to refactor allOf inline schemas into $ref. (v7.0.0 will skip the refactoring of these allOf inline schemas by default)
- `RESOLVE_INLINE_ENUMS=true` will refactor inline enum definitions into $ref
- `RESOLVE_INLINE_ENUMS=true` will refactor inline enum definitions into $ref. This must be activated to allow the renaming of inline enum definitions using `inlineSchemaMappings`.
## OpenAPI Normalizer
@@ -601,11 +601,29 @@ Example:
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer REMOVE_X_INTERNAL=true
```
- `FILTER`: When set to `operationId:addPet|getPetById` for example, it will add `x-internal:true` to operations with operationId not equal to addPet/getPetById (which will have x-internal set to false) so that these operations marked as internal won't be generated.
- `FILTER`
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /tmp/java-okhttp/ --openapi-normalizer FILTER="operationId:addPet|getPetById"
The `FILTER` parameter allows selective inclusion of API operations based on specific criteria. It applies the `x-internal: true` property to operations that do **not** match the specified values, preventing them from being generated.
### Available Filters
- **`operationId`**
When set to `operationId:addPet|getPetById`, operations **not** matching `addPet` or `getPetById` will be marked as internal (`x-internal: true`), and excluded from generation. Matching operations will have `x-internal: false`.
- **`method`**
When set to `method:get|post`, operations **not** using `GET` or `POST` methods will be marked as internal (`x-internal: true`), preventing their generation.
- **`tag`**
When set to `tag:person|basic`, operations **not** tagged with `person` or `basic` will be marked as internal (`x-internal: true`), and will not be generated.
### Example Usage
```sh
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate \
-g java \
-i modules/openapi-generator/src/test/resources/3_0/petstore.yaml \
-o /tmp/java-okhttp/ \
--openapi-normalizer FILTER="operationId:addPet|getPetById"
```
- `SET_CONTAINER_TO_NULLABLE`: When set to `array|set|map` (or just `array`) for example, it will set `nullable` in array, set and map to true.

View File

@@ -54,6 +54,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|useIntForTimeout|Use int for Timeout (fall back to v7.9.0 templates). This option (for restsharp only) will be deprecated so please migrated to TimeSpan instead.| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false|
|useSourceGeneration|Use source generation where available (only `generichost` library supports this option).| |false|
|useVirtualForHooks|Generate code that exposes public virtual hooks on ApiClient to customize low-level HTTP requests (only `restsharp`. `httpclient` libraries support this option).| |false|
|validatable|Generates self-validatable models.| |true|
|zeroBasedEnums|Enumerations with string values will start from 0 when true, 1 when false. If not set, enumerations with string values will start from 0 if the first value is 'unknown', case insensitive.| |null|

View File

@@ -52,7 +52,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|errorObjectType|Error Object type. (This option is for okhttp-gson only)| |null|
|failOnUnknownProperties|Fail Jackson de-serialization on unknown properties| |false|
|generateBuilders|Whether to generate builders for models| |false|
|generateClientAsBean|For resttemplate, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false|
|generateClientAsBean|For resttemplate, restclient and webclient, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false|
|generateConstructorWithAllArgs|whether to generate a constructor for all arguments| |false|
|gradleProperties|Append additional Gradle properties to the gradle.properties file| |null|
|groupId|groupId in generated pom.xml| |org.openapitools|

View File

@@ -52,7 +52,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|errorObjectType|Error Object type. (This option is for okhttp-gson only)| |null|
|failOnUnknownProperties|Fail Jackson de-serialization on unknown properties| |false|
|generateBuilders|Whether to generate builders for models| |false|
|generateClientAsBean|For resttemplate, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false|
|generateClientAsBean|For resttemplate, restclient and webclient, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false|
|generateConstructorWithAllArgs|whether to generate a constructor for all arguments| |false|
|gradleProperties|Append additional Gradle properties to the gradle.properties file| |null|
|groupId|groupId in generated pom.xml| |org.openapitools|

View File

@@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|addJsonNameAnnotation|Append &quot;json_name&quot; annotation to message field when the specification name differs from the protobuf field name| |false|
|numberedFieldNumberList|Field numbers in order.| |false|
|startEnumsWithUnspecified|Introduces &quot;UNSPECIFIED&quot; as the first element of enumerations.| |false|

View File

@@ -22,7 +22,7 @@ npm install @openapitools/openapi-generator-cli -g
To install a specific version of the tool, pass the version during installation:
<!-- RELEASE_VERSION -->
```bash
openapi-generator-cli version-manager set 7.9.0
openapi-generator-cli version-manager set 7.12.0
```
<!-- /RELEASE_VERSION -->
To install the tool as a dev dependency in your current project:

View File

@@ -16,7 +16,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>7.9.0</version>
<version>7.12.0</version>
<executions>
<execution>
<goals>

9
intellij-codestyle.xml Normal file
View File

@@ -0,0 +1,9 @@
<code_scheme name="Project" version="173">
<JavaCodeStyleSettings>
<option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION" value="true" />
<option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION_IN_PARAMETER" value="true" />
</JavaCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="FIELD_ANNOTATION_WRAP" value="0" />
</codeStyleSettings>
</code_scheme>

View File

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

View File

@@ -1,7 +1,8 @@
package org.openapitools.codegen;
public class Constants {
private Constants(){ }
private Constants() {
}
public static final String CLI_NAME = "openapi-generator-cli";
public static final String GIT_REPO = "https://github.com/openapitools/openapi-generator";

View File

@@ -138,7 +138,7 @@ public class AuthorTemplate extends OpenApiGeneratorCommand {
} else {
LOGGER.warn("The library filter '{}' extracted an unexpected library path: {}", library, p.toAbsolutePath());
}
});
});
}
LOGGER.info("Extracted templates to '{}' directory. Refer to https://openapi-generator.tech/docs/templating for customization details.", outputDirPath);

View File

@@ -20,11 +20,7 @@ package org.openapitools.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
import org.openapitools.codegen.GeneratorNotFoundException;
import org.openapitools.codegen.VendorExtension;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.FeatureSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,10 +33,10 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
@SuppressWarnings({"unused","java:S106", "java:S1192"})
@SuppressWarnings({"unused", "java:S106", "java:S1192"})
@Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp extends OpenApiGeneratorCommand {
@@ -49,7 +45,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
private static final String FORMAT_TEXT = "text";
private static final String FORMAT_MARKDOWN = "markdown";
private static final String FORMAT_YAMLSAMPLE = "yamlsample";
private static final int FEATURE_SET_DISPLAY_WIDTH= 20;
private static final int FEATURE_SET_DISPLAY_WIDTH = 20;
@Option(name = {"-g",
"--generator-name"}, title = "generator name", description = "generator to get config help for")
@@ -121,7 +117,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
private Boolean markdownHeader;
@Option(name = {
"--supported-vendor-extensions"}, title = "supported vendor extensions", description = "List supported vendor extensions")
"--supported-vendor-extensions"}, title = "supported vendor extensions", description = "List supported vendor extensions")
private Boolean supportedVendorExtensions;
@Option(name = {"--full-details"}, title = "full generator details", description = "displays CLI options as well as other configs/mappings (implies --instantiation-types, --reserved-words, --language-specific-primitives, --import-mappings, --feature-set)")
@@ -241,16 +237,16 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
}
sb
.append(newline).append("## SUPPORTED VENDOR EXTENSIONS").append(newline).append(newline)
.append("| Extension name | Description | Applicable for | Default value |").append(newline)
.append("| -------------- | ----------- | -------------- | ------------- |").append(newline);
.append(newline).append("## SUPPORTED VENDOR EXTENSIONS").append(newline).append(newline)
.append("| Extension name | Description | Applicable for | Default value |").append(newline)
.append("| -------------- | ----------- | -------------- | ------------- |").append(newline);
supportedVendorExtensions.forEach(
extension -> sb.append("|").append(extension.getName())
.append("|").append(extension.getDescription())
.append("|").append(extension.getLevels().stream().map(Objects::toString).collect(Collectors.joining(", ")))
.append("|").append(extension.getDefaultValue())
.append(newline)
extension -> sb.append("|").append(extension.getName())
.append("|").append(extension.getDescription())
.append("|").append(extension.getLevels().stream().map(Objects::toString).collect(Collectors.joining(", ")))
.append("|").append(extension.getDefaultValue())
.append(newline)
);
sb.append(newline);
}
@@ -359,17 +355,17 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
sb.append("| Property | Value | Notes |").append(newline);
sb.append("| -------- | ----- | ----- |").append(newline);
sb.append("| generator name | "+config.getName()+" | pass this to the generate command after -g |").append(newline);
sb.append("| generator stability | "+config.getGeneratorMetadata().getStability()+" | |").append(newline);
sb.append("| generator type | "+config.getTag()+" | |").append(newline);
sb.append("| generator name | " + config.getName() + " | pass this to the generate command after -g |").append(newline);
sb.append("| generator stability | " + config.getGeneratorMetadata().getStability() + " | |").append(newline);
sb.append("| generator type | " + config.getTag() + " | |").append(newline);
if (config.generatorLanguage() != null) {
sb.append("| generator language | "+config.generatorLanguage().toString()+" | |").append(newline);
sb.append("| generator language | " + config.generatorLanguage().toString() + " | |").append(newline);
}
if (config.generatorLanguageVersion() != null) {
sb.append("| generator language version | "+config.generatorLanguageVersion()+" | |").append(newline);
sb.append("| generator language version | " + config.generatorLanguageVersion() + " | |").append(newline);
}
sb.append("| generator default templating engine | "+config.defaultTemplatingEngine()+" | |").append(newline);
sb.append("| helpTxt | "+config.getHelp()+" | |").append(newline);
sb.append("| generator default templating engine | " + config.defaultTemplatingEngine() + " | |").append(newline);
sb.append("| helpTxt | " + config.getHelp() + " | |").append(newline);
sb.append(newline);
}

View File

@@ -17,18 +17,10 @@
package org.openapitools.codegen.cmd;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.spi.FilterAttachable;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.config.CodegenConfigurator;
@@ -36,6 +28,14 @@ import org.openapitools.codegen.config.MergedSpecBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
@SuppressWarnings({"java:S106"})
@Command(name = "generate", description = "Generate code with the specified generator.")
public class Generate extends OpenApiGeneratorCommand {
@@ -101,7 +101,7 @@ public class Generate extends OpenApiGeneratorCommand {
+ "overwritten during the generation.")
private Boolean skipOverwrite;
@Option(name = { "--dry-run" }, title = "Dry run",
@Option(name = {"--dry-run"}, title = "Dry run",
description = "Try things out and report on potential changes (without actually making changes).")
private Boolean isDryRun;
@@ -327,15 +327,15 @@ public class Generate extends OpenApiGeneratorCommand {
private Boolean legacyDiscriminatorBehavior;
@Option(name = {"--minimal-update"},
title = "Minimal update",
description = "Only write output files that have changed.")
title = "Minimal update",
description = "Only write output files that have changed.")
private Boolean minimalUpdate;
@Override
public void execute() {
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
spec = new MergedSpecBuilder(inputSpecRootDirectory, StringUtils.isBlank(mergedFileName) ? "_merged_spec" : mergedFileName)
.buildMergedSpec();
.buildMergedSpec();
System.out.println("Merge input spec would be used - " + spec);
}

View File

@@ -18,7 +18,6 @@ package org.openapitools.codegen.cmd;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.*;
@@ -26,7 +25,6 @@ import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.TokenBuffer;
import io.airlift.airline.Arguments;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
@@ -211,7 +209,7 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
ClientOptInput opts = configurator.toClientOptInput();
CodegenConfig config = opts.getConfig();
name = config.getName();
Path target = Paths.get(config.getOutputDir());
Path updated = rootDir.resolve(target);
config.setOutputDir(updated.toString());
@@ -308,34 +306,34 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();
TokenBuffer buffer = new TokenBuffer(p);
recurse(buffer, p, codec, false);
JsonParser newParser = buffer.asParser(codec);
newParser.nextToken();
return super.deserialize(newParser, ctx);
}
private void recurse(TokenBuffer buffer, JsonParser p, ObjectMapper codec, boolean skipOuterbraces) throws IOException {
boolean firstToken = true;
JsonToken token;
JsonToken token;
while ((token = p.nextToken()) != null) {
String name = p.currentName();
if (skipOuterbraces && firstToken && JsonToken.START_OBJECT.equals(token)) {
continue;
}
if (skipOuterbraces && p.getParsingContext().inRoot() && JsonToken.END_OBJECT.equals(token)) {
continue;
}
if (JsonToken.VALUE_NULL.equals(token)) {
continue;
}
if (name != null && JsonToken.FIELD_NAME.equals(token) && name.startsWith(INCLUDE)) {
p.nextToken();
String fileName = p.getText();
@@ -348,7 +346,7 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
} else {
buffer.copyCurrentEvent(p);
}
firstToken = false;
}
}

View File

@@ -1,10 +1,8 @@
package org.openapitools.codegen.cmd;
import com.google.common.base.Objects;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
@@ -20,18 +18,18 @@ import java.util.stream.Collectors;
@Command(name = "list", description = "Lists the available generators")
public class ListGenerators extends OpenApiGeneratorCommand {
@Option(name = {"-s", "--short" }, description = "shortened output (suitable for scripting)")
@Option(name = {"-s", "--short"}, description = "shortened output (suitable for scripting)")
private Boolean shortened = false;
@Option(name = {"-d", "--docsite" }, description = "format for docusaurus site output", hidden = true)
@Option(name = {"-d", "--docsite"}, description = "format for docusaurus site output", hidden = true)
private Boolean docusaurus = false;
@Option(name = {"--github-nested-index" }, description = "format for github index at docs/generators/README.md", hidden = true)
private Boolean githubNestedIndex = false;
@Option(name = {"--github-nested-index"}, description = "format for github index at docs/generators/README.md", hidden = true)
private Boolean githubNestedIndex = false;
@Option(name = {"-i", "--include" },
@Option(name = {"-i", "--include"},
description = "comma-separated list of stability indexes to include (value: all,beta,stable,experimental,deprecated). Excludes deprecated by default.",
allowedValues = { "all", "beta", "stable", "experimental", "deprecated" })
allowedValues = {"all", "beta", "stable", "experimental", "deprecated"})
private String include = "stable,beta,experimental";
@Override
@@ -88,7 +86,7 @@ public class ListGenerators extends OpenApiGeneratorCommand {
.sorted(Comparator.comparing(CodegenConfig::getName))
.collect(Collectors.toList());
if(!list.isEmpty()) {
if (!list.isEmpty()) {
if (docusaurus || githubNestedIndex) {
sb.append("## ").append(typeName).append(" generators");
} else {

View File

@@ -17,9 +17,7 @@
package org.openapitools.codegen.cmd;
import static ch.lambdaj.collection.LambdaCollections.with;
import static com.google.common.base.Joiner.on;
import ch.lambdaj.function.convert.Converter;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -31,9 +29,9 @@ import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.TemplateManager;
import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
import org.openapitools.codegen.templating.MustacheEngineAdapter;
import org.openapitools.codegen.templating.TemplateManagerOptions;
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,7 +41,8 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import ch.lambdaj.function.convert.Converter;
import static ch.lambdaj.collection.LambdaCollections.with;
import static com.google.common.base.Joiner.on;
/**
* User: lanwen Date: 24.03.15 Time: 20:22
@@ -99,19 +98,19 @@ public class Meta extends OpenApiGeneratorCommand {
new SupportingFile("kotlin/generatorClassTest.mustache", on(File.separator).join("src/test/kotlin", asPath(targetPackage)), mainClass.concat("Test.kt")),
new SupportingFile("kotlin/README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"),
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()))
: ImmutableList.of(
new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
new SupportingFile("README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));
new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
new SupportingFile("README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"),
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));
String currentVersion = buildInfo.getVersion();
@@ -134,11 +133,11 @@ public class Meta extends OpenApiGeneratorCommand {
* destination directory
*
* @param targetDir - destination directory
* @param data - map with additional params needed to process templates
* @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj
*/
private static Converter<SupportingFile, File> processFiles(final File targetDir,
final Map<String, Object> data) {
final Map<String, Object> data) {
return support -> {
try {
File destinationFolder =
@@ -148,7 +147,7 @@ public class Meta extends OpenApiGeneratorCommand {
TemplateManager templateProcessor = new TemplateManager(
new TemplateManagerOptions(false, false),
new MustacheEngineAdapter(),
new TemplatePathLocator[]{ new CommonTemplateContentLocator("codegen") }
new TemplatePathLocator[]{new CommonTemplateContentLocator("codegen")}
);
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.getTemplateFile()).getPath());

View File

@@ -19,12 +19,13 @@ package org.openapitools.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import org.apache.commons.text.WordUtils;
import org.openapitools.codegen.auth.AuthParser;
import org.openapitools.codegen.validation.ValidationResult;
import org.openapitools.codegen.validations.oas.OpenApiEvaluator;
import org.openapitools.codegen.validations.oas.RuleConfiguration;
@@ -33,7 +34,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
@SuppressWarnings({"unused","java:S106"})
@SuppressWarnings({"unused", "java:S106"})
@Command(name = "validate", description = "Validate specification")
public class Validate extends OpenApiGeneratorCommand {
@@ -41,15 +42,23 @@ public class Validate extends OpenApiGeneratorCommand {
description = "location of the OpenAPI spec, as URL or file (required)")
private String spec;
@Option(name = { "--recommend"}, title = "recommend spec improvements")
@Option(name = {"--recommend"}, title = "recommend spec improvements")
private Boolean recommend;
@Option(
name = {"-a", "--auth"},
title = "authorization",
description = "adds authorization headers when fetching the OpenAPI definitions remotely. "
+ "Pass in a URL-encoded string of name:header with a comma separating multiple values")
private String auth;
@Override
public void execute() {
System.out.println("Validating spec (" + spec + ")");
ParseOptions options = new ParseOptions();
options.setResolve(true);
SwaggerParseResult result = new OpenAPIParser().readLocation(spec, null, options);
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
SwaggerParseResult result = new OpenAPIParser().readLocation(spec, authorizationValues, options);
List<String> messageList = result.getMessages();
Set<String> errors = new HashSet<>(messageList);
Set<String> warnings = new HashSet<>();

View File

@@ -20,7 +20,7 @@ public class AuthorTemplateTest {
}
@Test
public void smokeTestAuthorTemplateCommand(){
public void smokeTestAuthorTemplateCommand() {
Cli.CliBuilder<Runnable> builder = createBuilder();
String[] arguments = new String[]{
"author",
@@ -57,7 +57,7 @@ public class AuthorTemplateTest {
Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/okhttp-gson/auth/RetryingOAuth.mustache")));
}
private Cli.CliBuilder<Runnable> createBuilder(){
private Cli.CliBuilder<Runnable> createBuilder() {
Cli.CliBuilder<Runnable> builder = new Cli.CliBuilder<>("openapi-generator-cli");
builder.withGroup("author")

View File

@@ -42,7 +42,7 @@ public class GenerateBatchTest {
@DataProvider(name = "customIncludeDeserializerFiles")
public Object[][] customIncludeDeserializerFiles() {
return new Object[][] {
return new Object[][]{
{JAXRS_DATELIB_J8_JSON},
{JAXRS_DATELIB_J8_YAML},
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML},
@@ -89,7 +89,7 @@ public class GenerateBatchTest {
@SuppressWarnings("unused")
@Test(
expectedExceptions = { RuntimeException.class },
expectedExceptions = {RuntimeException.class},
expectedExceptionsMessageRegExp = "Unable to deserialize config file: .*"
)
public void testInvalidDeserializerWithIncludeOption() {

View File

@@ -363,7 +363,7 @@ public class GenerateTest {
verify(configurator).toContext();
verifyNoMoreInteractions(configurator);
} finally {
if(!f.delete()) {
if (!f.delete()) {
System.out.println("Directory didn't delete. You can ignore this.");
}
}
@@ -389,7 +389,7 @@ public class GenerateTest {
verify(configurator).toClientOptInput();
verify(configurator).toContext();
verifyNoMoreInteractions(configurator);
if(!f.delete()) {
if (!f.delete()) {
System.out.println("Directory didn't delete. You can ignore this.");
}
}

View File

@@ -17,8 +17,8 @@
package org.openapitools.codegen.cmd.utils;
import org.openapitools.codegen.utils.OptionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.utils.OptionUtils;
import org.testng.annotations.Test;
import java.util.Collections;

View File

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

View File

@@ -27,7 +27,6 @@ public abstract class AbstractTemplatingEngineAdapter implements TemplatingEngin
* Gets all possible template paths for a given location.
*
* @param location The full location of the template.
*
* @return A new array of locations, modified according to the extensions or other adapter rules.
*/
protected String[] getModifiedFileLocation(String location) {
@@ -44,7 +43,6 @@ public abstract class AbstractTemplatingEngineAdapter implements TemplatingEngin
* Returns the path without an extension for an input location.
*
* @param location The location of the file, with original file extension intact.
*
* @return The full path, without extension (e.g. /path/to/file.txt => /path/to/file)
*/
private String getPathWithoutExtension(String location) {

View File

@@ -17,7 +17,7 @@ public class TemplateDefinition {
/**
* <p>Constructor for TemplateDefinition.</p>
*
* @param templateFile a template path relative to user template or embedded template.
* @param templateFile a template path relative to user template or embedded template.
* @param destinationFilename a target output location for the file, relative to the output directory.
*/
public TemplateDefinition(String templateFile, String destinationFilename) {
@@ -34,8 +34,8 @@ public class TemplateDefinition {
/**
* <p>Constructor for TemplateDefinition.</p>
*
* @param templateFile a template path relative to user template or embedded template.
* @param folder a folder in the target output directory in which to place the target file.
* @param templateFile a template path relative to user template or embedded template.
* @param folder a folder in the target output directory in which to place the target file.
* @param destinationFilename a target output location for the file, relative to the output directory.
*/
public TemplateDefinition(String templateFile, String folder, String destinationFilename) {
@@ -94,7 +94,9 @@ public class TemplateDefinition {
this.templateType = templateType;
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -106,13 +108,17 @@ public class TemplateDefinition {
getTemplateType() == that.getTemplateType();
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType());
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]")

View File

@@ -17,16 +17,22 @@ public enum TemplateFileType {
private final String templateType;
TemplateFileType(String templateType) { this.templateType = templateType; }
TemplateFileType(String templateType) {
this.templateType = templateType;
}
/**
* Returns the value for this template file type
*
* @return The template type of this enum.
*/
public String value() { return this.templateType; }
public String value() {
return this.templateType;
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return new StringJoiner(", ", TemplateFileType.class.getSimpleName() + "[", "]")

View File

@@ -12,10 +12,9 @@ public interface TemplateProcessor {
/**
* Writes data to a compiled template
*
* @param data Input data
* @param data Input data
* @param template Input template location
* @param target The targeted file output location
*
* @param target The targeted file output location
* @return The actual file
* @throws IOException If file cannot be written.
*/
@@ -34,7 +33,7 @@ public interface TemplateProcessor {
/**
* Allow a caller to mark a path as ignored with accompanying reason
*
* @param path The ignored path
* @param path The ignored path
* @param context The reason for ignoring this path
*/
void ignore(Path path, String context);
@@ -42,7 +41,7 @@ public interface TemplateProcessor {
/**
* Allow a caller to mark a path as skipped with accompanying reason
*
* @param path The skipped path
* @param path The skipped path
* @param context The reason for skipping this path
*/
void skip(Path path, String context);
@@ -50,8 +49,9 @@ public interface TemplateProcessor {
/**
* Allow a caller to mark a path having errored during processing with accompanying reason
*
* @param path The path which has caused an error
* @param path The path which has caused an error
* @param context The reason for the error
*/
default void error(Path path, String context) { }
default void error(Path path, String context) {
}
}

View File

@@ -47,8 +47,8 @@ public interface TemplatingEngineAdapter {
/**
* Determine if the adapter handles compilation of the file
* @param filename The template filename
*
* @param filename The template filename
* @return True if the file should be compiled by this adapter, else false.
*/
default boolean handlesFile(String filename) {
@@ -58,7 +58,7 @@ public interface TemplatingEngineAdapter {
/**
* Compiles a template into a string
*
* @param executor From where we can fetch the templates content (e.g. an instance of DefaultGenerator)
* @param executor From where we can fetch the templates content (e.g. an instance of DefaultGenerator)
* @param bundle The map of values to pass to the template
* @param templateFile The name of the template (e.g. model.mustache )
* @return the processed template result

View File

@@ -17,6 +17,7 @@
package org.openapitools.codegen.api;
// TODO: 6.0 Remove
/**
* interface to the full template content
* implementers might take into account the -t cli option,

View File

@@ -340,7 +340,7 @@ public class WorkflowSettings {
* @return a reference to this Builder
*/
public Builder withOutputDir(String outputDir) {
if (outputDir != null ) {
if (outputDir != null) {
this.outputDir = Paths.get(outputDir).toAbsolutePath().toString();
} else {
this.outputDir = DEFAULT_OUTPUT_DIR;
@@ -473,7 +473,7 @@ public class WorkflowSettings {
// check to see if the folder exists
if (f.exists() && f.isDirectory()) {
uri = f.toURI();
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
} else {
String cpDir;
// HACK: this duplicates TemplateManager.getCPResourcePath a bit. We should probably move that function to core.
@@ -543,7 +543,7 @@ public class WorkflowSettings {
/**
* Sets the {@code globalProperties} and returns a reference to this Builder so that the methods can be chained together.
*
* @param key The key of a system (global) property to set
* @param key The key of a system (global) property to set
* @param value The value of a system (global) property to set
* @return a reference to this Builder
*/

View File

@@ -383,7 +383,6 @@ public class FeatureSet {
* Includes the defined {@link ClientModificationFeature} to the new/existing set of supported features.
*
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
@@ -395,7 +394,6 @@ public class FeatureSet {
* Excludes the defined {@link ClientModificationFeature} from the set of supported features.
*
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
@@ -422,7 +420,6 @@ public class FeatureSet {
* Includes the defined {@link DataTypeFeature} to the new/existing set of supported features.
*
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
@@ -434,7 +431,6 @@ public class FeatureSet {
* Excludes the defined {@link DataTypeFeature} from the set of supported features.
*
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
@@ -461,7 +457,6 @@ public class FeatureSet {
* Includes the defined {@link DocumentationFeature} to the new/existing set of supported features.
*
* @param documentationFeature One or more {@code documentationFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeDocumentationFeatures(DocumentationFeature... documentationFeature) {
@@ -473,7 +468,6 @@ public class FeatureSet {
* Excludes the defined {@link DocumentationFeature} from the set of supported features.
*
* @param documentationFeature One or more {@code documentationFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeDocumentationFeatures(DocumentationFeature... documentationFeature) {
@@ -500,7 +494,6 @@ public class FeatureSet {
* Includes the defined {@link SchemaSupportFeature} to the new/existing set of supported features.
*
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
@@ -512,7 +505,6 @@ public class FeatureSet {
* Excludes the defined {@link SchemaSupportFeature} from the set of supported features.
*
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
@@ -539,7 +531,6 @@ public class FeatureSet {
* Includes the defined {@link ParameterFeature} to the new/existing set of supported features.
*
* @param parameterFeature One or more {@code parameterFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeParameterFeatures(ParameterFeature... parameterFeature) {
@@ -551,7 +542,6 @@ public class FeatureSet {
* Excludes the defined {@link ParameterFeature} from the set of supported features.
*
* @param parameterFeature One or more {@code parameterFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeParameterFeatures(ParameterFeature... parameterFeature) {
@@ -578,7 +568,6 @@ public class FeatureSet {
* Includes the defined {@link SecurityFeature} to the new/existing set of supported features.
*
* @param securityFeature One or more {@code securityFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeSecurityFeatures(SecurityFeature... securityFeature) {
@@ -590,7 +579,6 @@ public class FeatureSet {
* Excludes the defined {@link SecurityFeature} from the set of supported features.
*
* @param securityFeature One or more {@code securityFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeSecurityFeatures(SecurityFeature... securityFeature) {
@@ -617,7 +605,6 @@ public class FeatureSet {
* Includes the defined {@link GlobalFeature} to the new/existing set of supported features.
*
* @param globalFeature One or more {@code globalFeatures} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeGlobalFeatures(GlobalFeature... globalFeature) {
@@ -629,7 +616,6 @@ public class FeatureSet {
* Excludes the defined {@link GlobalFeature} from the set of supported features.
*
* @param globalFeature One or more {@code globalFeatures} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeGlobalFeatures(GlobalFeature... globalFeature) {
@@ -656,7 +642,6 @@ public class FeatureSet {
* Includes the defined {@link WireFormatFeature} to the new/existing set of supported features.
*
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {
@@ -672,7 +657,6 @@ public class FeatureSet {
* </p>
*
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {

View File

@@ -49,10 +49,12 @@ public enum Stability {
*
* @return The descriptive value of this enum.
*/
public String value() { return description; }
public String value() {
return description;
}
public static Stability forDescription(String description) {
for (Stability value: values()) {
for (Stability value : values()) {
if (value.description.equals(description)) {
return value;
}

View File

@@ -23,7 +23,7 @@ import org.openapitools.codegen.meta.features.annotations.ToolingExtension;
/**
* Defines common data types supported by a generator.
* Some of these features are defined in specs, and some are specific to the tool.
*
* <p>
* Where data types are listed as tool-specific, this either indicates that the data type is common enough that it is an officially
* supported custom data type by the toolset (see {@link DataTypeFeature#Decimal}), or that the consideration of a special type isn't
* explicitly mentioned by the specification(s) but differs enough across languages that it warrants a special callout (see {@link DataTypeFeature#ArrayOfModel}).
@@ -114,9 +114,9 @@ public enum DataTypeFeature {
*
*
* <p>
* This should be used as an indicator for password best practices, such as assigning a variable to
* a character array rather than string, avoiding logging the variable in clear text, and masking the value
* in any user inputs. See OWASP for best practices.
* This should be used as an indicator for password best practices, such as assigning a variable to
* a character array rather than string, avoiding logging the variable in clear text, and masking the value
* in any user inputs. See OWASP for best practices.
* </p>
*/
@OAS2 @OAS3

View File

@@ -129,7 +129,7 @@ public enum GlobalFeature {
*
* <p>
* NOTE: This option is more relevant for documentation generators which support HTML stylesheets, but may be used
* to determine structural characteristics of a property (as with OAS 3.x lack of collectionFormat).
* to determine structural characteristics of a property (as with OAS 3.x lack of collectionFormat).
* </p>
*/
@OAS3

View File

@@ -45,7 +45,7 @@ public enum ParameterFeature {
* Supports body parameters.
*
* <p>
* OAS 3.x specification supports this structurally rather than as an "in" parameter.
* OAS 3.x specification supports this structurally rather than as an "in" parameter.
* </p>
*/
@OAS2
@@ -53,7 +53,7 @@ public enum ParameterFeature {
/**
* Supports form encoded parameters.
*
* <p>
* OAS 3.x specification supports this structurally via content types rather than as an "in" parameter.
*/
@OAS2

View File

@@ -54,11 +54,11 @@ public enum SchemaSupportFeature {
*
* <p>
* This means that a single "Type" in generated code may refer to one of any type in a set of 2 or more types.
*
* <p>
* This is defined as a union as "OneOf" support is not explicitly limited to physical boundaries in OpenAPI Specification. The
* implementation of such a type is easily represented dynamically (a JSON object), but requires explicit language support and
* potentially a custom implementation (typed instances).
*
* <p>
* Note that a generator may support "Unions" very loosely by returning an Object/Any/ref/interface{} type, leaving onus
* on type determination to the consumer. This does *NOT* suggest generated code implements a "Union Type".
* </p>

View File

@@ -4,9 +4,9 @@ public enum AnnotationType {
OAS2, OAS3, ToolingExtension;
public static AnnotationType fromAnnotation(Class<?> input) {
if(input == OAS2.class) return AnnotationType.OAS2;
if(input == OAS3.class) return AnnotationType.OAS3;
if(input == ToolingExtension.class) return AnnotationType.ToolingExtension;
if (input == OAS2.class) return AnnotationType.OAS2;
if (input == OAS3.class) return AnnotationType.OAS3;
if (input == ToolingExtension.class) return AnnotationType.ToolingExtension;
return null;
}
}

View File

@@ -39,7 +39,6 @@ public class GenericValidator<TInput> implements Validator<TInput> {
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
*
* @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/
@Override

View File

@@ -28,7 +28,7 @@ public final class Invalid extends Validated {
/**
* Constructs a new {@link Invalid} instance.
*
* @param rule The rule which was evaluated and resulted in this state.
* @param rule The rule which was evaluated and resulted in this state.
* @param message The message to be displayed for this invalid state.
*/
Invalid(ValidationRule rule, String message) {
@@ -39,7 +39,7 @@ public final class Invalid extends Validated {
/**
* Constructs a new {@link Invalid} instance.
*
* @param rule The rule which was evaluated and resulted in this state.
* @param rule The rule which was evaluated and resulted in this state.
* @param message The message to be displayed for this invalid state.
* @param details Additional contextual details related to the invalid state.
*/

View File

@@ -46,21 +46,20 @@ public abstract class Validated {
/**
* Creates an instance of an {@link Invalid} validation state.
*
* @param rule The rule which was evaluated.
* @param rule The rule which was evaluated.
* @param message The message to display to a user.
*
* @return A {@link Validated} instance representing an invalid state according to the rule.
*/
public static Validated invalid(ValidationRule rule, String message) {
return new Invalid(rule, message);
}
/**
* Creates an instance of an {@link Invalid} validation state.
*
* @param rule The rule which was evaluated.
* @param rule The rule which was evaluated.
* @param message The message to display to a user.
* @param details Additional contextual details related to the invalid state.
*
* @return A {@link Validated} instance representing an invalid state according to the rule.
*/
public static Validated invalid(ValidationRule rule, String message, String details) {
@@ -71,7 +70,6 @@ public abstract class Validated {
* Creates an instance of an {@link Valid} validation state.
*
* @param rule The rule which was evaluated.
*
* @return A {@link Validated} instance representing a valid state according to the rule.
*/
public static Validated valid(ValidationRule rule) {

View File

@@ -49,7 +49,7 @@ public final class ValidationResult {
* @return All validated results.
*/
public List<Validated> getAll() {
return validations;
return validations;
}
/**
@@ -57,8 +57,8 @@ public final class ValidationResult {
*
* @return A list containing only {@link Valid} states.
*/
public List<Valid> getValid(){
return validations.stream().filter(Validated::isValid).map(it -> (Valid)it).collect(Collectors.toList());
public List<Valid> getValid() {
return validations.stream().filter(Validated::isValid).map(it -> (Valid) it).collect(Collectors.toList());
}
/**
@@ -66,10 +66,10 @@ public final class ValidationResult {
*
* @return A list of all validation errors.
*/
public List<Invalid> getErrors(){
public List<Invalid> getErrors() {
return validations.stream()
.filter(it -> !it.isValid())
.map(it -> (Invalid)it)
.map(it -> (Invalid) it)
.filter(it -> it.getSeverity().equals(Severity.ERROR))
.collect(Collectors.toList());
}
@@ -79,10 +79,10 @@ public final class ValidationResult {
*
* @return A list of all validation warnings.
*/
public List<Invalid> getWarnings(){
public List<Invalid> getWarnings() {
return validations.stream()
.filter(it -> !it.isValid())
.map(it -> (Invalid)it)
.map(it -> (Invalid) it)
.filter(it -> it.getSeverity().equals(Severity.WARNING))
.collect(Collectors.toList());
}

View File

@@ -31,11 +31,11 @@ public class ValidationRule {
/**
* Constructs a new instance of {@link ValidationRule}
*
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param test The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param test The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
*/
ValidationRule(Severity severity, String description, String failureMessage, Function<Object, Result> test) {
this.severity = severity;
@@ -57,7 +57,6 @@ public class ValidationRule {
* Evaluate an instance of an object against this rule.
*
* @param input The instance to be evaluated.
*
* @return <code>true</code> if the object state is valid according to this rule, otherwise <code>false</code>.
*/
public Result evaluate(Object input) {
@@ -90,19 +89,18 @@ public class ValidationRule {
* @return An "empty" rule.
*/
static ValidationRule empty() {
return new ValidationRule(Severity.ERROR, "empty", "failure message", (i) -> Fail.empty() );
return new ValidationRule(Severity.ERROR, "empty", "failure message", (i) -> Fail.empty());
}
/**
* Create an instance of a {@link ValidationRule}
*
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
@@ -114,10 +112,9 @@ public class ValidationRule {
* Create an instance of a {@link ValidationRule} which should result in an error should the evaluate of this rule fail.
*
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
@@ -128,12 +125,11 @@ public class ValidationRule {
/**
* Create an instance of a {@link ValidationRule} which should result in a warning should the evaluate of this rule fail.
*
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
@@ -164,17 +160,24 @@ public class ValidationRule {
}
public abstract boolean passed();
public final boolean failed() { return !passed(); }
public final boolean failed() {
return !passed();
}
public Throwable getThrowable() {
return throwable;
}
public boolean thrown() { return this.throwable == null; }
public boolean thrown() {
return this.throwable == null;
}
}
public static final class Pass extends Result {
public static Result empty() { return new Pass(); }
public static Result empty() {
return new Pass();
}
public Pass() {
super();
@@ -192,7 +195,9 @@ public class ValidationRule {
}
public static final class Fail extends Result {
public static Result empty() { return new Fail(); }
public static Result empty() {
return new Fail();
}
public Fail() {
super();

View File

@@ -27,7 +27,6 @@ public interface Validator<TInput> {
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
*
* @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/
ValidationResult validate(TInput input);

View File

@@ -25,7 +25,7 @@ import static org.testng.Assert.*;
public class WorkflowSettingsTest {
@Test
public void defaultValuesNotOverriddenByNulls(){
public void defaultValuesNotOverriddenByNulls() {
WorkflowSettings settings = WorkflowSettings.newBuilder()
.withOutputDir(null)
.withVerbose(null)
@@ -50,7 +50,7 @@ public class WorkflowSettingsTest {
}
@Test
public void newBuilderFromCopyShouldMutateGlobalProperties(){
public void newBuilderFromCopyShouldMutateGlobalProperties() {
WorkflowSettings original = WorkflowSettings.newBuilder()
.withOutputDir("output")
.withVerbose(true)
@@ -110,16 +110,17 @@ public class WorkflowSettingsTest {
}
@Test
public void defaultValuesCanBeChangedClassConstructor(){
public void defaultValuesCanBeChangedClassConstructor() {
WorkflowSettings defaults = new WorkflowSettings();
assertOnChangesToDefaults(defaults);
}
@Test
public void defaultValuesCanBeChangedBuilder(){
public void defaultValuesCanBeChangedBuilder() {
WorkflowSettings defaults = WorkflowSettings.newBuilder().build();
assertOnChangesToDefaults(defaults);
}
@Test
public void customOutputDirIsSet() {
WorkflowSettings settings = WorkflowSettings.newBuilder()

View File

@@ -18,12 +18,13 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class GenericValidatorTest {
static class Person {
private int age;
@@ -53,7 +54,7 @@ public class GenericValidatorTest {
}
private static ValidationRule.Result checkNameNormalLength(Person person) {
return person.name.length() < 10? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
return person.name.length() < 10 ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
}
private List<ValidationRule> validationRules = Arrays.asList(
@@ -65,7 +66,7 @@ public class GenericValidatorTest {
);
@Test
public void testGenericValidatorSuccesses(){
public void testGenericValidatorSuccesses() {
Person person = new Person("Jim", 23);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
@@ -79,7 +80,7 @@ public class GenericValidatorTest {
}
@Test
public void testGenericValidatorSingleConditionFails(){
public void testGenericValidatorSingleConditionFails() {
Person person = new Person("Jim", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
@@ -98,7 +99,7 @@ public class GenericValidatorTest {
}
@Test
public void testGenericValidatorMultipleConditionsFail(){
public void testGenericValidatorMultipleConditionsFail() {
Person person = new Person("asdf", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
@@ -122,7 +123,7 @@ public class GenericValidatorTest {
}
@Test
public void testGenericValidatorErrorsAndWarnings(){
public void testGenericValidatorErrorsAndWarnings() {
Person person = new Person("0123456789asdfghjkl", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);

View File

@@ -18,17 +18,18 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class ValidatedTest {
@Test
public void isValidTrueForValidType(){
public void isValidTrueForValidType() {
boolean isValid = Validated.valid(ValidationRule.empty()).isValid();
assertTrue(isValid);
}
@Test
public void isValidFalseForInvalidType(){
public void isValidFalseForInvalidType() {
boolean isValid = Validated.invalid(ValidationRule.empty(), "test").isValid();
assertFalse(isValid);
}

View File

@@ -18,7 +18,8 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class ValidationRuleTest {
static class Sample {
@@ -39,11 +40,11 @@ public class ValidationRuleTest {
private static ValidationRule.Result checkPattern(Sample input) {
String pattern = "^[A-Z][a-z]*$";
return (input.getName() != null && input.getName().matches(pattern)) ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
return (input.getName() != null && input.getName().matches(pattern)) ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
}
@Test
public void createMethodUsingMethodReference(){
public void createMethodUsingMethodReference() {
Sample nil = new Sample(null);
Sample six = new Sample("123456");
Sample seven = new Sample("1234567");
@@ -56,11 +57,11 @@ public class ValidationRuleTest {
}
@Test
public void createMethodUsingLambda(){
public void createMethodUsingLambda() {
Sample nil = new Sample(null);
Sample lowercase = new Sample("jim");
Sample titlecase = new Sample("Jim");
ValidationRule result = ValidationRule.error("test", i -> checkPattern((Sample)i));
ValidationRule result = ValidationRule.error("test", i -> checkPattern((Sample) i));
assertFalse(result.evaluate(nil).passed());
assertFalse(result.evaluate(lowercase).passed());
assertTrue(result.evaluate(titlecase).passed());

View File

@@ -97,7 +97,7 @@ task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.Valid
[source,group]
----
plugins {
id "org.openapi.generator" version "7.10.0"
id "org.openapi.generator" version "7.12.0"
}
----

View File

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

View File

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

View File

@@ -19,5 +19,5 @@ gradle generateGoWithInvalidSpec # expected outcome: BUILD FAILED
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=7.10.0 openApiValidate
gradle -PopenApiGeneratorVersion=7.12.0 openApiValidate
```

View File

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

View File

@@ -12,7 +12,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.10.0</version>
<version>7.12.0</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.12.0</version>
<version>7.13.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>
@@ -217,8 +217,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>2.2.16</swagger-annotations-version>
<jersey-version>2.35</jersey-version>
<jackson-version>2.15.2</jackson-version>
<jackson-databind-version>2.15.2</jackson-databind-version>
<jackson-version>2.17.1</jackson-version>
<jackson-databind-version>2.17.1</jackson-databind-version>
<jackson-databind-nullable-version>0.2.6</jackson-databind-nullable-version>
<jakarta-annotation-version>1.3.5</jakarta-annotation-version>
<junit-version>4.13.2</junit-version>

View File

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

View File

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

View File

@@ -15,7 +15,7 @@
<properties>
<swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>2.35</jersey-version>
<jackson-version>2.15.2</jackson-version>
<jackson-version>2.17.1</jackson-version>
<jackson-databind-nullable-version>0.2.1</jackson-databind-nullable-version>
<jodatime-version>2.7</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>

View File

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

View File

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

View File

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

View File

@@ -5,7 +5,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.12.0</version>
<version>7.13.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../../pom.xml</relativePath>
</parent>
@@ -20,9 +20,9 @@
</properties>
<dependencies>
<dependency>
<groupId>org.sonatype.plexus</groupId>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-build-api</artifactId>
<version>0.0.7</version>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>

View File

@@ -24,19 +24,23 @@ import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.parser.OpenAPIResolver;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import io.swagger.v3.parser.core.models.ParseOptions;
import lombok.Setter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.*;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.openapitools.codegen.*;
import org.openapitools.codegen.auth.AuthParser;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.config.MergedSpecBuilder;
@@ -47,7 +51,10 @@ import org.sonatype.plexus.build.incremental.DefaultBuildContext;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.MessageFormat;
@@ -154,7 +161,7 @@ public class CodeGenMojo extends AbstractMojo {
/**
* The name of templating engine to use, "mustache" (default) or "handlebars" (beta)
*/
@Parameter(name = "engine", defaultValue = "mustache", property="openapi.generator.maven.plugin.engine")
@Parameter(name = "engine", defaultValue = "mustache", property = "openapi.generator.maven.plugin.engine")
private String engine;
/**
@@ -539,7 +546,7 @@ public class CodeGenMojo extends AbstractMojo {
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
inputSpec = new MergedSpecBuilder(inputSpecRootDirectory, mergedFileName)
.buildMergedSpec();
.buildMergedSpec();
LOGGER.info("Merge input spec would be used - {}", inputSpec);
}
@@ -570,7 +577,7 @@ public class CodeGenMojo extends AbstractMojo {
return;
}
if (buildContext != null && inputSpec != null ) {
if (buildContext != null && inputSpec != null) {
if (buildContext.isIncremental() &&
inputSpecFile.exists() &&
!buildContext.hasDelta(inputSpecFile)) {
@@ -662,7 +669,7 @@ public class CodeGenMojo extends AbstractMojo {
configurator.setEnablePostProcessFile(enablePostProcessFile);
}
if (generateAliasAsModel != null) {
if (generateAliasAsModel != null) {
configurator.setGenerateAliasAsModel(generateAliasAsModel);
}
@@ -972,7 +979,7 @@ public class CodeGenMojo extends AbstractMojo {
File parent = new File(storedInputSpecHashFile.getParent());
if (!parent.mkdirs()) {
throw new RuntimeException("Failed to create the folder " + parent.getAbsolutePath() +
" to store the checksum of the input spec.");
" to store the checksum of the input spec.");
}
}
@@ -991,7 +998,7 @@ public class CodeGenMojo extends AbstractMojo {
}
/**
* Calculate an SHA256 hash for the openapi specification.
* Calculate an SHA256 hash for the openapi specification.
* If the specification is hosted on a remote resource it is downloaded first.
*
* @param inputSpec - Openapi specification input file. Can denote a URL or file path.
@@ -1000,16 +1007,19 @@ public class CodeGenMojo extends AbstractMojo {
private String calculateInputSpecHash(String inputSpec) {
final ParseOptions parseOptions = new ParseOptions();
parseOptions.setResolve(true);
final URL remoteUrl = inputSpecRemoteUrl();
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
return Hashing.sha256().hashBytes(
new OpenAPIParser().readLocation(remoteUrl == null ? inputSpec : remoteUrl.toString(), null, parseOptions)
.getOpenAPI().toString().getBytes(StandardCharsets.UTF_8)
new OpenAPIParser().readLocation(remoteUrl == null ? inputSpec : remoteUrl.toString(), authorizationValues, parseOptions)
.getOpenAPI().toString().getBytes(StandardCharsets.UTF_8)
).toString();
}
/**
* Try to parse inputSpec setting string into URL
*
* @return A valid URL or null if inputSpec is not a valid URL
*/
private URL inputSpecRemoteUrl() {
@@ -1022,8 +1032,9 @@ public class CodeGenMojo extends AbstractMojo {
/**
* Get specification hash file
*
* @param inputSpecFile - Openapi specification input file to calculate its hash.
* Does not take into account if input spec is hosted on remote resource
* Does not take into account if input spec is hosted on remote resource
* @return a file with previously calculated hash
*/
private File getHashFile(File inputSpecFile) {
@@ -1089,7 +1100,9 @@ public class CodeGenMojo extends AbstractMojo {
// Merge the OpenAPI spec file.
final var parseOptions = new ParseOptions();
parseOptions.setResolve(true);
final var openApiMerged = new OpenAPIResolver(new OpenAPIV3Parser().readLocation(inputSpec, null, parseOptions).getOpenAPI()).resolve();
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
final var openApiMerged = new OpenAPIResolver(new OpenAPIV3Parser().readLocation(inputSpec, authorizationValues, parseOptions).getOpenAPI()).resolve();
// Switch based on JSON or YAML.
final var extension = inputSpec.toLowerCase(Locale.ROOT).endsWith(".json") ? ".json" : ".yaml";

View File

@@ -94,13 +94,13 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
assertTrue(Files.exists(tempDir.resolve(
"target/generated-sources/common-maven/remote-openapi/.openapi-generator/petstore.yaml-executionId.sha256"
"target/generated-sources/common-maven/remote-openapi/.openapi-generator/petstore.yaml-executionId.sha256"
)));
}
/**
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
* test that the spec is not regenerated when the hash has not changed.
* test that the spec is not regenerated when the hash has not changed.
*/
public void testSkipRegenerationForClasspathSpecFileNoChange() throws Exception {
//GIVEN
@@ -114,7 +114,7 @@ public class CodeGenMojoTest extends BaseTestCase {
/* Check the hash file was created */
final Path generatedDir = tempDir.resolve("target/generated-sources/common-maven/remote-openapi");
assertTrue(Files.exists(
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256")
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256")
));
/* Remove the generated source */
@@ -134,7 +134,7 @@ public class CodeGenMojoTest extends BaseTestCase {
/**
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
* test that the generated source is regenerated when the hash has changed.
* test that the generated source is regenerated when the hash has changed.
*/
public void testSkipRegenerationForClasspathSpecFileWithChange() throws Exception {
//GIVEN
@@ -151,12 +151,12 @@ public class CodeGenMojoTest extends BaseTestCase {
/* Update the hash contents to be a different value, simulating a spec change */
Files.write(
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256"),
List.of("bd1bf4a953c858f9d47b67ed6029daacf1707e5cbd3d2e4b01383ba30363366f")
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256"),
List.of("bd1bf4a953c858f9d47b67ed6029daacf1707e5cbd3d2e4b01383ba30363366f")
);
/* Remove the generated source */
try(Stream<Path> files = Files.walk(generatedDir.resolve("src"))) {
try (Stream<Path> files = Files.walk(generatedDir.resolve("src"))) {
//noinspection ResultOfMethodCallIgnored
files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
}
@@ -181,7 +181,7 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
assertTrue(Files.exists(
tempDir.resolve("target/generated-sources/common-maven/remote-openapi/petstore-full-spec.yaml")
tempDir.resolve("target/generated-sources/common-maven/remote-openapi/petstore-full-spec.yaml")
));
}
@@ -194,8 +194,8 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
List<Artifact> matchingArtifacts = mojo.mavenProject.getAttachedArtifacts().stream()
.filter(artifact -> artifact.getFile().getName().equals("petstore-full-spec.yaml"))
.collect(Collectors.toList());
.filter(artifact -> artifact.getFile().getName().equals("petstore-full-spec.yaml"))
.collect(Collectors.toList());
assertEquals(1, matchingArtifacts.size());
}
@@ -242,7 +242,7 @@ public class CodeGenMojoTest extends BaseTestCase {
var currentHash = Files.readString(hashFile); // read hash
FileUtils.deleteDirectory(generatedDir.resolve("src").toFile()); // Remove the generated source
Files.writeString( // change schema definition in external file
tempDir.resolve("schemas/Pet.yaml"),"\n wrapped: true", StandardOpenOption.APPEND
tempDir.resolve("schemas/Pet.yaml"), "\n wrapped: true", StandardOpenOption.APPEND
);
// WHEN
@@ -250,8 +250,8 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
assertNotEquals(
Files.readString(hashFile), currentHash, "Checksum should not be the same after external file change"
);
Files.readString(hashFile), currentHash, "Checksum should not be the same after external file change"
);
assertTrue("Src directory should have been regenerated", Files.exists(generatedDir.resolve("src")));
}
@@ -269,7 +269,7 @@ public class CodeGenMojoTest extends BaseTestCase {
}
private MojoExecution copyWithExecutionId(String executionId, MojoExecution execution) {
MojoExecution executionWithId = new MojoExecution(execution.getMojoDescriptor(), executionId);
MojoExecution executionWithId = new MojoExecution(execution.getMojoDescriptor(), executionId);
executionWithId.setConfiguration(execution.getConfiguration());
return executionWithId;
}
@@ -278,18 +278,18 @@ public class CodeGenMojoTest extends BaseTestCase {
LocalRepository localRepo = new LocalRepository(basedir.resolve("local-repo").toFile());
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
session.setLocalRepositoryManager(
new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer()).newInstance(session, localRepo)
new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer()).newInstance(session, localRepo)
);
MavenExecutionRequest request = new DefaultMavenExecutionRequest().setBaseDirectory(basedir.toFile());
if (profile != null) {
request.addActiveProfile(profile);
}
ProjectBuildingRequest configuration = request.getProjectBuildingRequest()
.setRepositorySession(session)
.setResolveDependencies(true);
.setRepositorySession(session)
.setResolveDependencies(true);
MavenProject project = lookup(ProjectBuilder.class)
.build(basedir.resolve("pom.xml").toFile(), configuration)
.getProject();
.build(basedir.resolve("pom.xml").toFile(), configuration)
.getProject();
assertNotNull(project);
return project;
}

View File

@@ -20,6 +20,6 @@ import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
public class CommonMavenProjectStub extends MavenProjectStub {
public CommonMavenProjectStub() {
StubUtility.configureStub(this,"common-maven", "common-maven.xml");
StubUtility.configureStub(this, "common-maven", "common-maven.xml");
}
}

View File

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

View File

@@ -28,7 +28,7 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
@ComponentScan(basePackages = { "org.openapitools.codegen.online", "org.openapitools.codegen.online.api", "org.openapitools.codegen.online.configuration"})
@ComponentScan(basePackages = {"org.openapitools.codegen.online", "org.openapitools.codegen.online.api", "org.openapitools.codegen.online.configuration"})
public class OpenAPI2SpringBoot implements CommandLineRunner {
@Override

View File

@@ -26,14 +26,14 @@ import java.util.Date;
public class RFC3339DateFormat extends ISO8601DateFormat {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
// Same as ISO8601DateFormat but serializing milliseconds.
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true);
toAppendTo.append(value);
return toAppendTo;
}
// Same as ISO8601DateFormat but serializing milliseconds.
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true);
toAppendTo.append(value);
return toAppendTo;
}
}

View File

@@ -17,16 +17,15 @@
package org.openapitools.codegen.online.api;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiOriginFilter implements javax.servlet.Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

View File

@@ -42,9 +42,9 @@ import java.util.Map;
public interface GenApi {
GenApiDelegate getDelegate();
@ApiOperation(value = "Gets languages supported by the client generator", nickname = "clientOptions", notes = "", response = String.class, responseContainer = "List", tags={ "clients", })
@ApiOperation(value = "Gets languages supported by the client generator", nickname = "clientOptions", notes = "", response = String.class, responseContainer = "List", tags = {"clients",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List") })
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List")})
@RequestMapping(value = "/gen/clients",
method = RequestMethod.GET)
default ResponseEntity<List<String>> clientOptions() {
@@ -52,62 +52,62 @@ public interface GenApi {
}
@ApiOperation(value = "Downloads a pre-generated file", nickname = "downloadFile", notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST operations. The fileId code can be used just once, after which a new `fileId` will need to be requested.", response = MultipartFile.class, tags={ "clients","servers", })
@ApiOperation(value = "Downloads a pre-generated file", nickname = "downloadFile", notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST operations. The fileId code can be used just once, after which a new `fileId` will need to be requested.", response = MultipartFile.class, tags = {"clients", "servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = MultipartFile.class) })
@ApiResponse(code = 200, message = "successful operation", response = MultipartFile.class)})
@RequestMapping(value = "/gen/download/{fileId}",
produces = { "application/octet-stream" },
produces = {"application/octet-stream"},
method = RequestMethod.GET)
default ResponseEntity<Resource> downloadFile(@ApiParam(value = "",required=true) @PathVariable("fileId") String fileId) {
default ResponseEntity<Resource> downloadFile(@ApiParam(value = "", required = true) @PathVariable("fileId") String fileId) {
return getDelegate().downloadFile(fileId);
}
@ApiOperation(value = "Generates a client library", nickname = "generateClient", notes = "Accepts a `GeneratorInput` options map for spec location and generation options", response = ResponseCode.class, tags={ "clients", })
@ApiOperation(value = "Generates a client library", nickname = "generateClient", notes = "Accepts a `GeneratorInput` options map for spec location and generation options", response = ResponseCode.class, tags = {"clients",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class) })
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class)})
@RequestMapping(value = "/gen/clients/{language}",
method = RequestMethod.POST)
default ResponseEntity<ResponseCode> generateClient(@ApiParam(value = "The target language for the client library",required=true) @PathVariable("language") String language,@ApiParam(value = "Configuration for building the client library" ,required=true ) @Valid @RequestBody GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateClient(@ApiParam(value = "The target language for the client library", required = true) @PathVariable("language") String language, @ApiParam(value = "Configuration for building the client library", required = true) @Valid @RequestBody GeneratorInput generatorInput) {
return getDelegate().generateClient(language, generatorInput);
}
@ApiOperation(value = "Generates a server library", nickname = "generateServerForLanguage", notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", response = ResponseCode.class, tags={ "servers", })
@ApiOperation(value = "Generates a server library", nickname = "generateServerForLanguage", notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", response = ResponseCode.class, tags = {"servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class) })
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class)})
@RequestMapping(value = "/gen/servers/{framework}",
method = RequestMethod.POST)
default ResponseEntity<ResponseCode> generateServerForLanguage(@ApiParam(value = "framework",required=true) @PathVariable("framework") String framework,@ApiParam(value = "parameters" ,required=true ) @Valid @RequestBody GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateServerForLanguage(@ApiParam(value = "framework", required = true) @PathVariable("framework") String framework, @ApiParam(value = "parameters", required = true) @Valid @RequestBody GeneratorInput generatorInput) {
return getDelegate().generateServerForLanguage(framework, generatorInput);
}
@ApiOperation(value = "Returns options for a client library", nickname = "getClientOptions", notes = "", tags={ "clients", })
@ApiOperation(value = "Returns options for a client library", nickname = "getClientOptions", notes = "", tags = {"clients",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") })
@ApiResponse(code = 200, message = "successful operation")})
@RequestMapping(value = "/gen/clients/{language}",
produces = { "application/json" },
produces = {"application/json"},
method = RequestMethod.GET)
default ResponseEntity<Map<String, CliOption>> getClientOptions(@ApiParam(value = "The target language for the client library",required=true) @PathVariable("language") String language) {
default ResponseEntity<Map<String, CliOption>> getClientOptions(@ApiParam(value = "The target language for the client library", required = true) @PathVariable("language") String language) {
return getDelegate().getClientOptions(language);
}
@ApiOperation(value = "Returns options for a server framework", nickname = "getServerOptions", notes = "", tags={ "servers", })
@ApiOperation(value = "Returns options for a server framework", nickname = "getServerOptions", notes = "", tags = {"servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") })
@ApiResponse(code = 200, message = "successful operation")})
@RequestMapping(value = "/gen/servers/{framework}",
produces = { "application/json" },
produces = {"application/json"},
method = RequestMethod.GET)
default ResponseEntity<Map<String, CliOption>> getServerOptions(@ApiParam(value = "The target language for the server framework",required=true) @PathVariable("framework") String framework) {
default ResponseEntity<Map<String, CliOption>> getServerOptions(@ApiParam(value = "The target language for the server framework", required = true) @PathVariable("framework") String framework) {
return getDelegate().getServerOptions(framework);
}
@ApiOperation(value = "Gets languages supported by the server generator", nickname = "serverOptions", notes = "", response = String.class, responseContainer = "List", tags={ "servers", })
@ApiOperation(value = "Gets languages supported by the server generator", nickname = "serverOptions", notes = "", response = String.class, responseContainer = "List", tags = {"servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List") })
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List")})
@RequestMapping(value = "/gen/servers",
method = RequestMethod.GET)
default ResponseEntity<List<String>> serverOptions() {

View File

@@ -42,12 +42,12 @@ public interface GenApiDelegate {
}
/**
* @see GenApi#clientOptions
* @return A {@link ResponseEntity} listing options for the target client generator.
* @see GenApi#clientOptions
*/
default ResponseEntity<List<String>> clientOptions() {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
break;
@@ -60,24 +60,24 @@ public interface GenApiDelegate {
/**
* @param fileId The unique id of the file, provided in a {@link ResponseCode} response.
* @see GenApi#downloadFile
* @return A {@link ResponseEntity} of the requested {@link Resource}.
* @see GenApi#downloadFile
*/
default ResponseEntity<Resource> downloadFile(String fileId) {
default ResponseEntity<Resource> downloadFile(String fileId) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
/**
* @param language The target generator (language is a misnomer here, but kept for API consistency).
* @param language The target generator (language is a misnomer here, but kept for API consistency).
* @param generatorInput The configuration settings to be used during client generation.
* @see GenApi#generateClient
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested client code.
* @see GenApi#generateClient
*/
default ResponseEntity<ResponseCode> generateClient( String language,
GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateClient(String language,
GeneratorInput generatorInput) {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
break;
@@ -89,15 +89,15 @@ public interface GenApiDelegate {
}
/**
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
* @param generatorInput The configuration settings to be used during server generation.
* @see GenApi#generateServerForLanguage
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested server code.
* @see GenApi#generateServerForLanguage
*/
default ResponseEntity<ResponseCode> generateServerForLanguage( String framework,
GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateServerForLanguage(String framework,
GeneratorInput generatorInput) {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
break;
@@ -110,31 +110,31 @@ public interface GenApiDelegate {
/**
* @param language The target generator (language is a misnomer here, but kept for API consistency).
* @see GenApi#getClientOptions
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by language (generator name).
* @see GenApi#getClientOptions
*/
default ResponseEntity<Map<String, CliOption>> getClientOptions(String language) {
default ResponseEntity<Map<String, CliOption>> getClientOptions(String language) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
/**
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
* @see GenApi#getServerOptions
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by framework (generator name).
* @see GenApi#getServerOptions
*/
default ResponseEntity<Map<String, CliOption>> getServerOptions( String framework) {
default ResponseEntity<Map<String, CliOption>> getServerOptions(String framework) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
/**
* @see GenApi#serverOptions
* @return A {@link ResponseEntity} listing options for the target server generator.
* @see GenApi#serverOptions
*/
default ResponseEntity<List<String>> serverOptions() {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
break;

View File

@@ -18,6 +18,9 @@
package org.openapitools.codegen.online.configuration;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
@@ -28,17 +31,14 @@ import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.HashSet;
@Configuration
@@ -59,22 +59,22 @@ public class OpenAPIDocumentationConfig {
String version = properties.getProperty("version", "unknown");
return new ApiInfoBuilder()
.title("OpenAPI Generator Online")
.description("This is an online openapi generator server. You can find out more at https://github.com/OpenAPITools/openapi-generator.")
.license("Apache 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version(version)
.contact(new Contact("","", ""))
.build();
.title("OpenAPI Generator Online")
.description("This is an online openapi generator server. You can find out more at https://github.com/OpenAPITools/openapi-generator.")
.license("Apache 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version(version)
.contact(new Contact("", "", ""))
.build();
}
@Bean
public Docket customImplementation(){
public Docket customImplementation() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api"))
.build()
.apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api"))
.build()
.forCodeGeneration(true)
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
@@ -99,7 +99,7 @@ public class OpenAPIDocumentationConfig {
docket.host(authority);
}
docket.pathMapping(hostURI.getPath());
} catch(URISyntaxException e) {
} catch (URISyntaxException e) {
LOGGER.warn("Could not parse configured GENERATOR_HOST '" + hostString + "': " + e.getMessage());
}
}

View File

@@ -35,7 +35,8 @@ public class ApiResponse {
@Getter String type;
@Getter String message;
public ApiResponse() {}
public ApiResponse() {
}
public ApiResponse(int code, String message) {
this.code = code;

View File

@@ -20,7 +20,8 @@ package org.openapitools.codegen.online.model;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
@Getter
@Setter
public class Generated {
private String filename;
private String friendlyName;

View File

@@ -22,7 +22,9 @@ import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter @NoArgsConstructor @AllArgsConstructor
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ResponseCode {
private String code;
private String link;

View File

@@ -22,11 +22,7 @@ import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import io.swagger.v3.parser.core.models.ParseOptions;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.*;
import org.openapitools.codegen.online.model.GeneratorInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,11 +31,7 @@ import org.springframework.web.server.ResponseStatusException;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.*;
public class Generator {
private static Logger LOGGER = LoggerFactory.getLogger(Generator.class);
@@ -49,7 +41,7 @@ public class Generator {
try {
config = CodegenConfigLoader.forName(language);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT,"Unsupported target %s supplied. %s",
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT, "Unsupported target %s supplied. %s",
language, e));
}
Map<String, CliOption> map = new LinkedHashMap<>();
@@ -82,7 +74,7 @@ public class Generator {
}
private static String generate(String language, GeneratorInput opts, Type type) {
LOGGER.debug(String.format(Locale.ROOT,"generate %s for %s", type.getTypeName(), language));
LOGGER.debug(String.format(Locale.ROOT, "generate %s for %s", type.getTypeName(), language));
if (opts == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No options were supplied");
}
@@ -141,13 +133,13 @@ public class Generator {
codegenConfig.additionalProperties().put("openAPI", openapi);
}
if(opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()){
for(String rule: opts.getOpenapiNormalizer()){
if (opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()) {
for (String rule : opts.getOpenapiNormalizer()) {
String[] ruleOperands = rule.split("=");
if(ruleOperands.length != 2) {
if (ruleOperands.length != 2) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "In rule: " + rule + "the operands were not provided in the form of <Rule>=<Value>");
}
codegenConfig.openapiNormalizer().put(ruleOperands[0],ruleOperands[1]);
codegenConfig.openapiNormalizer().put(ruleOperands[0], ruleOperands[1]);
}
}

View File

@@ -17,12 +17,7 @@
package org.openapitools.codegen.online.service;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -32,7 +27,6 @@ import java.util.zip.ZipOutputStream;
* sub files and sub directories, recursively.
*
* @author Ha Minh Nam
*
*/
public class ZipUtil {
/**
@@ -43,10 +37,10 @@ public class ZipUtil {
/**
* Compresses a collection of files to a destination zip file.
*
* @param listFiles A collection of files and directories
* @param listFiles A collection of files and directories
* @param destZipFile The path of the destination zip file
* @throws FileNotFoundException if file not found
* @throws IOException if IO exception occurs
* @throws IOException if IO exception occurs
*/
public void compressFiles(List<File> listFiles, String destZipFile)
throws IOException {
@@ -69,11 +63,11 @@ public class ZipUtil {
/**
* Adds a directory to the current zip output stream.
*
* @param folder the directory to be added
* @param folder the directory to be added
* @param parentFolder the path of parent directory
* @param zos the current zip output stream
* @param zos the current zip output stream
* @throws FileNotFoundException if file not found
* @throws IOException if IO exception occurs
* @throws IOException if IO exception occurs
*/
private void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos)
throws FileNotFoundException, IOException {
@@ -103,9 +97,9 @@ public class ZipUtil {
* Adds a file to the current zip output stream.
*
* @param file the file to be added
* @param zos the current zip output stream
* @param zos the current zip output stream
* @throws FileNotFoundException if file not found
* @throws IOException if IO exception occurs
* @throws IOException if IO exception occurs
*/
private static void addFileToZip(File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {

View File

@@ -88,8 +88,8 @@ public class GenApiControllerTest {
private void generateAndDownload(String type, String name) throws Exception {
String result = mockMvc.perform(post("http://test.com:1234/api/gen/" + type + "/" + name)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.contentType(MediaType.APPLICATION_JSON)
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
@@ -107,11 +107,11 @@ public class GenApiControllerTest {
@Test
public void generateWIthForwardedHeaders() throws Exception {
String result = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Forwarded-Proto", "https")
.header("X-Forwarded-Host", "forwarded.com")
.header("X-Forwarded-Port", "5678")
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.contentType(MediaType.APPLICATION_JSON)
.header("X-Forwarded-Proto", "https")
.header("X-Forwarded-Host", "forwarded.com")
.header("X-Forwarded-Port", "5678")
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
@@ -141,8 +141,8 @@ public class GenApiControllerTest {
String withoutOpenAPINormalizer = "{\"openAPIUrl\":\"https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml\",\"options\":{},\"spec\":{}}";
String responseOfNormalized = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
.contentType(MediaType.APPLICATION_JSON)
.content(withOpenAPINormalizer))
.contentType(MediaType.APPLICATION_JSON)
.content(withOpenAPINormalizer))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String codeOfNormalized = new ObjectMapper().readValue(responseOfNormalized, ResponseCode.class).getCode();
Long lengthOfNormalized = Long.parseLong(mockMvc.perform(get("http://test.com:1234/api/gen/download/" + codeOfNormalized))
@@ -159,7 +159,7 @@ public class GenApiControllerTest {
.andExpect(content().contentType("application/zip"))
.andExpect(status().isOk()).andReturn().getResponse().getHeader("Content-Length"));
Assert.isTrue(lengthOfNormalized <= lengthOfNotNormalized,"Using the normalizer should result in a smaller or equal file size");
Assert.isTrue(lengthOfNormalized <= lengthOfNotNormalized, "Using the normalizer should result in a smaller or equal file size");
}
}

View File

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

View File

@@ -60,7 +60,7 @@ public class CliOption {
}
public void setOptValue(String optValue) {
if (this.enumValues!=null && this.enumValues.containsKey(optValue)) {
if (this.enumValues != null && this.enumValues.containsKey(optValue)) {
this.optValue = optValue;
} else {
this.optValue = null;
@@ -88,7 +88,7 @@ public class CliOption {
/**
* Create new boolean command line option with a default of false
*
* @param opt Option name
* @param opt Option name
* @param description Option description
* @return the CliOption created
*/
@@ -99,8 +99,8 @@ public class CliOption {
/**
* Create new boolean command line option with the provided value as default
*
* @param opt Option name
* @param description Option description
* @param opt Option name
* @param description Option description
* @param defaultValue the default value to use if option not specified
* @return the CliOption created
*/
@@ -115,7 +115,7 @@ public class CliOption {
@JsonIgnore
public String getOptionHelp() {
StringBuilder sb = new StringBuilder(description);
if(defaultValue != null) {
if (defaultValue != null) {
sb.append(" (Default: ").append(defaultValue).append(")");
}
if (enumValues != null) {

View File

@@ -19,7 +19,6 @@ package org.openapitools.codegen;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import lombok.Getter;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.auth.AuthParser;
@@ -84,8 +83,8 @@ public class ClientOptInput {
/**
* Sets the generator/config instance
*
* @deprecated use {@link #config(CodegenConfig)} instead
* @param config codegen config
* @deprecated use {@link #config(CodegenConfig)} instead
*/
@Deprecated
public void setConfig(CodegenConfig config) {
@@ -118,8 +117,8 @@ public class ClientOptInput {
/**
* Sets the OpenAPI document
*
* @deprecated use {@link #openAPI(OpenAPI)} instead
* @param openAPI the specification
* @deprecated use {@link #openAPI(OpenAPI)} instead
*/
@Deprecated
public void setOpenAPI(OpenAPI openAPI) {

View File

@@ -38,6 +38,7 @@ public class CodegenCallback {
return Objects.equals(that.expression, expression) &&
Objects.equals(that.requests, requests) && Objects.equals(that.vendorExtensions, vendorExtensions);
}
@Override
public int hashCode() {
return Objects.hash(expression, requests, vendorExtensions);

View File

@@ -19,9 +19,11 @@ package org.openapitools.codegen;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
import java.util.List;
import java.util.Objects;
@Getter @Setter
@Getter
@Setter
public class CodegenComposedSchemas {
private List<CodegenProperty> allOf;
private List<CodegenProperty> oneOf;

View File

@@ -286,6 +286,9 @@ public class CodegenConstants {
public static final String SUPPORTS_ASYNC = "supportsAsync";
public static final String SUPPORTS_ASYNC_DESC = "Generate code that supports async operations.";
public static final String USE_VIRTUAL_FOR_HOOKS = "useVirtualForHooks";
public static final String USE_VIRTUAL_FOR_HOOKS_DESC = "Generate code that exposes public virtual hooks on ApiClient to customize low-level HTTP requests (only `restsharp`. `httpclient` libraries support this option).";
public static final String EXCLUDE_TESTS = "excludeTests";
public static final String EXCLUDE_TESTS_DESC = "Specifies that no tests are to be generated.";
@@ -372,9 +375,9 @@ public class CodegenConstants {
public static final String GENERATE_ALIAS_AS_MODEL = "generateAliasAsModel";
public static final String GENERATE_ALIAS_AS_MODEL_DESC = "Generate model implementation for aliases to map and array schemas. " +
"An 'alias' is an array, map, or list which is defined inline in a OpenAPI document and becomes a model in the generated code. " +
"A 'map' schema is an object that can have undeclared properties, i.e. the 'additionalproperties' attribute is set on that object. " +
"An 'array' schema is a list of sub schemas in a OAS document";
"An 'alias' is an array, map, or list which is defined inline in a OpenAPI document and becomes a model in the generated code. " +
"A 'map' schema is an object that can have undeclared properties, i.e. the 'additionalproperties' attribute is set on that object. " +
"An 'array' schema is a list of sub schemas in a OAS document";
public static final String USE_COMPARE_NET_OBJECTS = "useCompareNetObjects";
public static final String USE_COMPARE_NET_OBJECTS_DESC = "Use KellermanSoftware.CompareNetObjects for deep recursive object comparison. WARNING: this option incurs potential performance impact.";
@@ -405,16 +408,16 @@ public class CodegenConstants {
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT = "disallowAdditionalPropertiesIfNotPresent";
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC =
"If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. " +
"If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.";
"If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. " +
"If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.";
public static final String UNSUPPORTED_V310_SPEC_MSG =
"OpenAPI 3.1 support is still in beta. To report an issue related to 3.1 spec, please kindly open an issue in the Github repo: https://github.com/openAPITools/openapi-generator.";
"OpenAPI 3.1 support is still in beta. To report an issue related to 3.1 spec, please kindly open an issue in the Github repo: https://github.com/openAPITools/openapi-generator.";
public static final String ENUM_UNKNOWN_DEFAULT_CASE = "enumUnknownDefaultCase";
public static final String ENUM_UNKNOWN_DEFAULT_CASE_DESC =
"If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response." +
"With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.";
"With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP = "useOneOfDiscriminatorLookup";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC = "Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.";
@@ -438,7 +441,7 @@ public class CodegenConstants {
public static final String FASTAPI_IMPLEMENTATION_PACKAGE = "fastapiImplementationPackage";
public static final String WITH_XML = "withXml";
public static final String WITH_GO_MOD = "withGoMod";
public static final String GENERATE_MARSHAL_JSON = "generateMarshalJSON";

View File

@@ -8,7 +8,7 @@ import java.util.*;
/**
* This class encapsulates the OpenAPI discriminator construct, as specified at
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#discriminatorObject.
*
* <p>
* When request bodies or response payloads may be one of a number of different schemas,
* a discriminator object can be used to aid in serialization, deserialization, and validation.
* The discriminator is a specific object in a schema which is used to inform the consumer of
@@ -57,18 +57,18 @@ public class CodegenDiscriminator {
public void setIsEnum(boolean isEnum) {
this.isEnum = isEnum;
}
/**
* An object to hold discriminator mappings between payload values and schema names or
* references.
*
* <p>
* In the OpenAPI document, the discriminator "mapping" attribute is optional.
* In scenarios where the value of the discriminator field does not match the schema name
* or implicit mapping is not possible, an optional mapping definition MAY be used.
* In OpenAPITools codegen, the MappedModel is the union of all the discriminator mappings,
* both explicitly defined in the OpenAPI document and inherited from oneOf/allOf/anyOf.
*/
public static class MappedModel implements Comparable<MappedModel>{
public static class MappedModel implements Comparable<MappedModel> {
// The value of the discriminator property in the payload.
@Getter @Setter
private String mappingName;

View File

@@ -8,7 +8,8 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
@Getter public class CodegenMediaType {
@Getter
public class CodegenMediaType {
private CodegenProperty schema;
private LinkedHashMap<String, CodegenEncoding> encoding;
private HashMap<String, SchemaTestCase> testCases = new HashMap<>();
@@ -47,7 +48,7 @@ import java.util.Objects;
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodegenMediaType that = (CodegenMediaType) o;
return Objects.equals(schema,that.getSchema()) &&
return Objects.equals(schema, that.getSchema()) &&
Objects.equals(encoding, that.getEncoding()) &&
Objects.equals(vendorExtensions, that.vendorExtensions);
}

View File

@@ -19,13 +19,12 @@ package org.openapitools.codegen;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.v3.oas.models.ExternalDocumentation;
import java.util.*;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* CodegenModel represents a schema object in a OpenAPI document.
*/
@@ -85,39 +84,39 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public String unescapedDescription;
/**
* -- GETTER --
* Returns the discriminator for this schema object, or null if no discriminator has been specified.
* The list of all possible schema discriminator mapping values is obtained
* from explicit discriminator mapping values in the OpenAPI document, and from
* inherited discriminators through oneOf, allOf, anyOf.
* For example, a discriminator may be defined in a 'Pet' schema as shown below.
* The Dog and Cat schemas inherit the discriminator through the allOf reference.
* In the 'Pet' schema, the supported discriminator mapping values for the
* 'objectType' properties are 'Dog' and 'Cat'.
* The allowed discriminator mapping value for the Dog schema is 'Dog'.
* The allowed discriminator mapping value for the Cat schema is 'Dog'.
* Pet:
* type: object
* discriminator:
* propertyName: objectType
* required:
* - objectType
* properties:
* objectType:
* type: string
* Dog:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p1:
* type: string
* Cat:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p2:
* type: string
* Returns the discriminator for this schema object, or null if no discriminator has been specified.
* The list of all possible schema discriminator mapping values is obtained
* from explicit discriminator mapping values in the OpenAPI document, and from
* inherited discriminators through oneOf, allOf, anyOf.
* For example, a discriminator may be defined in a 'Pet' schema as shown below.
* The Dog and Cat schemas inherit the discriminator through the allOf reference.
* In the 'Pet' schema, the supported discriminator mapping values for the
* 'objectType' properties are 'Dog' and 'Cat'.
* The allowed discriminator mapping value for the Dog schema is 'Dog'.
* The allowed discriminator mapping value for the Cat schema is 'Dog'.
* Pet:
* type: object
* discriminator:
* propertyName: objectType
* required:
* - objectType
* properties:
* objectType:
* type: string
* Dog:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p1:
* type: string
* Cat:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p2:
* type: string
*
* @return the discriminator.
*/
@@ -174,7 +173,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public boolean isArray;
public boolean hasChildren;
public boolean isMap;
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
/**
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
*/
public boolean isOptional;
public boolean isNull;
public boolean isVoid = false;
@@ -208,7 +209,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
/**
* The type of the value for the additionalProperties keyword in the OAS document.
* Used in map like objects, including composed schemas.
*
* <p>
* In most programming languages, the additional (undeclared) properties are stored
* in a map data structure, such as HashMap in Java, map in golang, or a dict in Python.
* There are multiple ways to implement the additionalProperties keyword, depending
@@ -218,24 +219,23 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
* In that case 'CodegenModel.parent' is set to represent the class hierarchy.
* Another way is to use CodegenModel.additionalPropertiesType. A code generator
* such as Python does not use class inheritance to model additional properties.
*
* <p>
* For example, in the OAS schema below, the schema has a declared 'id' property
* and additional, undeclared properties of type 'integer' are allowed.
*
* <p>
* type: object
* properties:
* id:
* type: integer
* id:
* type: integer
* additionalProperties:
* type: integer
*
* type: integer
*/
@Getter @Setter
public String additionalPropertiesType;
/**
* True if additionalProperties is set to true (boolean value), any type, free form object, etc
*
* <p>
* TODO: we may rename this to isAdditionalPropertiesEnabled or something
* else to avoid confusions
*/
@@ -758,14 +758,22 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public boolean getIsUuid() { return isUuid; }
public boolean getIsUuid() {
return isUuid;
}
@Override
public void setIsUuid(boolean isUuid) { this.isUuid = isUuid; }
public void setIsUuid(boolean isUuid) {
this.isUuid = isUuid;
}
public boolean getIsUri() { return isUri; }
public boolean getIsUri() {
return isUri;
}
public void setIsUri(boolean isUri) { this.isUri = isUri; }
public void setIsUri(boolean isUri) {
this.isUri = isUri;
}
@Override
public void setComposedSchemas(CodegenComposedSchemas composedSchemas) {
@@ -833,7 +841,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public void setIsBinary(boolean isBinary) {}
public void setIsBinary(boolean isBinary) {
}
@Override
public boolean getIsByteArray() {
@@ -841,7 +850,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public void setIsByteArray(boolean isByteArray) {}
public void setIsByteArray(boolean isByteArray) {
}
@Override
public boolean getIsDecimal() {
@@ -1005,7 +1015,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
sb.append(", parent='").append(parent).append('\'');
sb.append(", parentSchema='").append(parentSchema).append('\'');
sb.append(", interfaces=").append(interfaces);
sb.append(", interfaceModels=").append(interfaceModels !=null ? interfaceModels.size() : "[]");
sb.append(", interfaceModels=").append(interfaceModels != null ? interfaceModels.size() : "[]");
sb.append(", allParents=").append(allParents);
sb.append(", parentModel=").append(parentModel);
sb.append(", children=").append(children != null ? children.size() : "[]");
@@ -1141,10 +1151,14 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public Map<String, CodegenProperty> getRequiredVarsMap() { return requiredVarsMap; }
public Map<String, CodegenProperty> getRequiredVarsMap() {
return requiredVarsMap;
}
@Override
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; }
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) {
this.requiredVarsMap = requiredVarsMap;
}
/**
* Remove duplicated properties in all variable list

View File

@@ -24,7 +24,8 @@ public final class CodegenModelFactory {
public static <T> T newInstance(CodegenModelType type) {
try {
return (T) type.getDefaultImplementation().getDeclaredConstructor().newInstance();
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException |
InvocationTargetException e) {
throw new RuntimeException(e);
}
}

View File

@@ -19,7 +19,8 @@ package org.openapitools.codegen;
import lombok.Getter;
@Getter public enum CodegenModelType {
@Getter
public enum CodegenModelType {
MODEL(CodegenModel.class),
OPERATION(CodegenOperation.class),

View File

@@ -220,7 +220,9 @@ public class CodegenOperation {
*
* @return true if responses contain only 1 entry and it's a default response, false otherwise
*/
public boolean getHasOnlyDefaultResponse() { return responses.size() == 1 && getHasDefaultResponse(); }
public boolean getHasOnlyDefaultResponse() {
return responses.size() == 1 && getHasDefaultResponse();
}
public boolean getAllResponsesAreErrors() {
return responses.stream().allMatch(response -> response.is4xx || response.is5xx);
@@ -237,7 +239,7 @@ public class CodegenOperation {
return null;
}
LinkedHashMap<String, CodegenMediaType> content = bodyParam.getContent();
for (String contentType: content.keySet()) {
for (String contentType : content.keySet()) {
contentTypeToOperation.put(contentType, this);
}
return contentTypeToOperation;

View File

@@ -17,17 +17,12 @@
package org.openapitools.codegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import io.swagger.v3.oas.models.examples.Example;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
/**
* Describes a single operation parameter in the OAS specification.
* A unique parameter is defined by a combination of a name and location.
@@ -50,7 +45,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary,
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isShort, isUnboundedInteger;
public boolean isArray, isMap;
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
/**
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
*/
public boolean isOptional;
public boolean isFile;
public boolean isEnum;
@@ -291,7 +288,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation,
getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(),
getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(),
getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull,isVoid,
getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, isVoid,
additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger,
hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content,
requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties,

View File

@@ -20,12 +20,7 @@ package org.openapitools.codegen;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperties {
/**
@@ -178,7 +173,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
public boolean isAnyType;
public boolean isArray;
public boolean isMap;
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
/**
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
*/
public boolean isOptional;
public boolean isEnum; // true if the enum is defined inline
public boolean isInnerEnum; // Enums declared inline will be located inside the generic model, changing how the enum is referenced in some cases.
@@ -243,7 +240,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
private boolean hasDiscriminatorWithNonEmptyMapping;
private CodegenComposedSchemas composedSchemas = null;
private boolean hasMultipleTypes = false;
/** true if the property's baseName != name, e.g. baseName = '_prop.value', name = 'propValue' after sanitization */
/**
* true if the property's baseName != name, e.g. baseName = '_prop.value', name = 'propValue' after sanitization
*/
private boolean hasSanitizedName = false;
private Map<String, CodegenProperty> requiredVarsMap;
private String ref;
@@ -849,7 +848,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
return hasSanitizedName;
}
public void setHasSanitizedName(boolean hasSanitizedName) { this.hasSanitizedName = hasSanitizedName; }
public void setHasSanitizedName(boolean hasSanitizedName) {
this.hasSanitizedName = hasSanitizedName;
}
@Override
public boolean getIsUuid() {

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